0

I have a DB in firebase with this structure (let's assume that the order in firebase is the same here):

"002f6b4a378caed3be3bd00346e3d380": {
  "id": "002f6b4a378caed3be3bd00346e3d380",
  "name": "Thayne",
  "date": 1516242371000,
  "totalDuration": 297
},
"8181554c6d4da1b7bfbb74aafe683b5d": {
  "id": "8181554c6d4da1b7bfbb74aafe683b5d",
  "name": "Marna",
  "date": 1517840087000,
  "totalDuration": 283
},
"d5d17675cae2b480020e0d43b9074658": {
  "id": "d5d17675cae2b480020e0d43b9074658",
  "name": "Clint",
  "date": 1515673469000,
  "totalDuration": 184
},
"9f2cdf88d59dd778d9aaa5745d10d1e2": {
  "id": "9f2cdf88d59dd778d9aaa5745d10d1e2",
  "name": "Nadia",
  "date": 1521918148000,
  "totalDuration": 234
},
"afc21c30da7b4ef3e88234cd7988f6a7": {
  "id": "afc21c30da7b4ef3e88234cd7988f6a7",
  "name": "Alexi",
  "date": 1519041073000,
  "totalDuration": 110
}

I have two int on each record, date and totalDuration, time is a UNIX timestamp and duration just a number that goes between 30 and 350.

I want to retrieve the list of all elements ordered by either one of this numbers. Going through the API and the docs I'm trying this:

var orderRef = firebase.database().ref("elements/");

orderRef.orderByChild('totalDuration').on("value", function(data){
  var result = data.val();
  for ( id in result ) {
    console.log( result[id].totalDuration );
  }
});

I'm expecting this:

110
184
234
283
297

Instead I'm getting the same order it already exists in the database:

297
283
234
110
184

Same goes for the date, it returns the data in the same order it exists in the database.

I'd like to know if there's something wrong with: a) My code, or b) My conception of how orderByChild actually works.

Rodrigo
  • 1,638
  • 1
  • 15
  • 27
  • I think this post would help https://stackoverflow.com/questions/33893866/orderbychild-not-working-in-firebase – goblin Mar 30 '18 at 21:19
  • Thanks @goblin, that does it. I was actually looking for a way to receive the data already ordered and not run extra code to add it to an object, but that'll do it certainly. Thanks again!!! – Rodrigo Mar 30 '18 at 21:24

0 Answers0