首页 文章

Node.js Firebase orderByChild无效

提问于
浏览
2

我试图找出这个嵌套的顺序,我所做的一切都不会起作用 .

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

{
  "-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),您可以执行"deep path query" . 在我的情况下,如果我想按 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());
    });
});

谢谢!

1 回答

  • 7

    在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());
        });
    });
    

相关问题