如何仅从FireBase查询返回ID?

时间:2015-12-16 01:20:29

标签: angularjs firebase angularfire

这是我的代码。它目前返回一个充满对象的数组。我怎样才能返回一个充满对象id的数组呢?

PDFKit.configure do |config|
  # if ["development"].include?(Rails.env)
  if ENV["TRIPCIPE_ENV"] == "local"
   config.wkhtmltopdf = Rails.root.join('bin', 'wkhtmltopdf').to_s
  else
   config.wkhtmltopdf = Rails.root.join('bin', 'wkhtmltopdf-amd64').to_s
  end  
 end

1 个答案:

答案 0 :(得分:1)

您的一些JSON对象(请在下次将这些问题添加到您的问题中):

  "20195": {
    "city": "ALTURAS",
    "digit1": "9",
    "digit2": "6",
    "digit3": "1",
    "digit4": "0",
    "digit5": "1",
    "population": "3969",
    "state": "CA",
    "zipCode": "96101"
  },
  "20196": {
    "city": "BLAIRSDEN-GRAEAGLE",
    "digit1": "9",
    "digit2": "6",
    "digit3": "1",
    "digit4": "0",
    "digit5": "3",
    "population": "1434",
    "state": "CA",
    "zipCode": "96103"
  },

您正在使用AngularFire,它构建于Firebase JavaScript SDK之上。该API将始终加载整个节点,它没有选项只能加载对象ID。

要获取ID,您有以下几种选择:

  1. 保留一份单独的ID列表,并从中加载。
  2. 使用REST API, which supports a shallow=true parameter
  3. 完全阻止查询,并为每个digit1
  4. 添加ID列表

    选项1很棘手,因为你做orderByChild()

    选项2也不起作用,因为您无法将shallow=true与其他查询参数合并。

    选项3可能性能最佳。你还有两个子选项:

    • 将整个对象存储在digit1

      "by_digit1":
        "9":
          "20195": {
            "city": "ALTURAS",
            "digit1": "9",
            "digit2": "6",
            "digit3": "1",
            "digit4": "0",
            "digit5": "1",
            "population": "3969",
            "state": "CA",
            "zipCode": "96101"
          },
          "20196": {
            "city": "BLAIRSDEN-GRAEAGLE",
            "digit1": "9",
            "digit2": "6",
            "digit3": "1",
            "digit4": "0",
            "digit5": "3",
            "population": "1434",
            "state": "CA",
            "zipCode": "96103"
          },
      
    • 仅存储“index”下每个对象的ID:

      "by_digit1":
        "9":
          "20195": true,
          "20196": true,
      

    使用这两种结构,您可以立即访问您要查找的项目列表:

    ref.child('by_digit1').child('9')
    

    使用最后一个结构,您将在主列表中查找每个城市。

    ref.child('by_digit1').child('9').on('value', function(snapshot) {
      snapshot.forEach(function(child) {
        var cityRef = ref.child('zips').child(child.key());
        cityRef.once('value', function(citySnapshot) {
          console.log(citySnapshot.val());
        });
      });
    })