4

enter image description here

above is a screenshot of my firebase database. i am trying to sort firebase data in descending order using negative timestamp. I 'm using the following command:

  const feedRef = database.ref('ducks')
  feedRef.orderByChild('timestamp').on('value', (snapshot, error) => {
    const feed = snapshot.val()})

i keep getting the feed in the same order as the database not in the descending order like i want.I think its not working because ducks endpoint doesnt have a child name timestamp how would i achieve this? Do the push generated keys have timestamp data ?

jasan
  • 11,475
  • 22
  • 57
  • 97

1 Answers1

7

When you call .val() on a snapshot, it gets converted into a JSON object. And the keys in a JavaScript object are by definition unordered (although many implementations will iterate the keys in lexicographical order).

If you run a query on the Firebase Database, you must ensure you don't convert it to JSON before you get the items in the right order. In your case, by using DataSnapshot.forEach():

const feedRef = database.ref('ducks')
var feed = [];
feedRef.orderByChild('timestamp').on('value', (snapshot, error) => {
    snapshot.forEach((duckSnap) => {
        const duck = duckSnap.val()
        console.log(duckSnap.key+'='+duck.name);
        feed.push(duck);
    });
    console.log(feed);
});
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • I may be wrong but shouldn't that be duckSnap.val(). also as i iterate over snapshot i should build another object by pushing data to it in the order i want? – jasan Jul 24 '16 at 05:05
  • 1
    I tried the following and still the order is still ascending ``database.ref('ducks').orderByChild('timestamp').on('value', (snapshot, error) => { let feed = {} snapshot.forEach((childSnapshot) => { feed[childSnapshot.key] = childSnapshot.val() }) console.log('ducks feed: ', feed)`` – jasan Jul 24 '16 at 05:20
  • The `snapshot.forEach()` will execute in the correct order.. But JSON is unordered. So if you put the ducks into `feed` based on their `childSnapshot.key`, the resulting `feed` object will be unordered again. I've expanded my answer to include a sample of that. – Frank van Puffelen Jul 24 '16 at 15:22
  • @jasan: inside the loop it should indeed use `duckSnap`. Thanks for pointing that out, I fixed it now (I don't know why your edit was rejects in review). – Frank van Puffelen Jul 26 '16 at 15:30