【问题标题】:Node.js + Firebase orderByChild not workingNode.js + Firebase orderByChild 不工作
【发布时间】:2016-11-02 14:17:58
【问题描述】:

我正在尝试找出这种嵌套排序,但我所做的一切都行不通。

这是我尝试订购的数据结构示例:

{
  "-KV_Lrm_93Agm8kAuXql": {
    "body": {
      "Acceleration": "0.0",
      "Altitude": "11",
      "Battery": "12.7",
      "Date": "2016/09/10",
      "order": 1,
      "time": "2016-10-19T20:26:32Z"
    }
  },
  "-KV_LuTfJ9VrKRHoRWuw": {
    "body": {
      "Acceleration": "0.0",
      "Altitude": "11",
      "Battery": "12.7",
      "Date": "2016/09/10",
      "order": 5,
      "time": "2016-10-21T20:26:32Z"
    }
  },
  "-KV_Lx9VABuEB8D3I-i1": {
    "body": {
      "Acceleration": "0.0",
      "Altitude": "11",
      "Battery": "12.7",
      "Date": "2016/09/10",
      "order": 2,
      "time": "2016-10-01T20:26:32Z"
    }
  },
  "-KV_LzQOM3rHEKQuwyHQ": {
    "body": {
      "Acceleration": "0.0",
      "Altitude": "11",
      "Battery": "12.7",
      "Date": "2016/09/10",
      "order": 10,
      "time": "2016-09-01T20:26:32Z"
    }
  },
  "-KV_M0fdznAbKanHoY91": {
    "body": {
      "Acceleration": "0.0",
      "Altitude": "11",
      "Battery": "12.7",
      "Date": "2016/09/10",
      "order": 6,
      "time": "2016-09-20T20:26:32Z"
    }
  }
}

根据 firebase 文档 (https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html),您可以执行“深度路径查询”。就我而言,如果我想按 order 排序,我应该可以这样做:

.orderByChild("body/order")

但这无济于事。它对结果的排序没有影响。我也尝试过按日期和时间订购,但都不起作用。这是我的完整节点功能。这将返回结果,只是未排序:

app.get('/api/xirgo-data', function(req, res) 
{
    var ref = db.ref("xirgo");
    ref
    .orderByChild("body/order")
    .on("value", function(snap) {
        return res.json(snap.val());
    });
});

谢谢!

【问题讨论】:

    标签: node.js firebase firebase-realtime-database


    【解决方案1】:

    当您在 Firebase 中请求查询的值时,生成的快照包含匹配子项的键、值和排序信息。

    但是当您随后将其转换为字典/关联数组/JavaScript 对象时,排序信息会丢失,因为 JavaScript 对象本质上是无序的。

    为确保您可以按正确顺序访问匹配项,请使用内置的DataSnapshot.forEach() 方法:

    var ref = db.ref("xirgo");
    ref
    .orderByChild("body/order")
    .on("value", function(snapshot) {
        snapshot.forEach(function(child) {
            console.log(child.key+': '+child.val());
        });
    });
    

    【讨论】:

    • 完美答案。
    猜你喜欢
    • 2017-05-05
    • 1970-01-01
    • 2018-02-07
    • 2019-07-01
    • 2016-02-26
    • 1970-01-01
    • 1970-01-01
    • 2017-08-22
    • 2020-12-26
    相关资源
    最近更新 更多