Jesse
Jesse

Reputation: 2684

Node.js + Firebase orderByChild not working

I am trying to figure out this nested ordering and nothing I do will work.

Here is a sample of the data structure I am trying to order:

{
  "-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"
    }
  }
}

Per the firebase documentation (https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html) you can do a "deep path query". In my case, if I want to sort by order I should be able to do:

.orderByChild("body/order")

But this does nothing. It has no effect on the ordering of the results. I have tried ordering on Date and time as well and neither work. Here is my full node function. This returns the results, just not ordered:

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

Thanks!

Upvotes: 2

Views: 2059

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598740

When you request the value of a query in Firebase, the resulting snapshot contains the keys, values and ordering information for the matching children.

But when you then convert this to a dictionary/associative array/JavaScript object, the ordering information is lost since JavaScript objects are inherently unordered.

To ensure you can access the matching items in the correct order, use the built-in DataSnapshot.forEach() method:

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

Upvotes: 11

Related Questions