charlestseng
charlestseng

Reputation: 21

Firesbase orderByChild doesn't work on timestamp

I want to use orderByChild on timestamp.
But it doesn't work well. They even sort by ascending or descending.

Here is the result :

enter image description here

And here is my code:

 toolboxesRef.orderByChild('timestamp').once('value', snapshot => {
    res.json(snapshot.val())
 })

I know I could use array to determine the data should sort by ascending or descending.
But know it even doesn't sorting. Does anyone know the problem?

Upvotes: 0

Views: 110

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598740

The order of properties in a JSON object is undefined. So as soon as you call snapshot.val(), the order of the child nodes is lost.

To maintain the order, use snapshot.forEach() to loop over the child nodes:

toolboxesRef.orderByChild('timestamp').once('value', snapshot => {
  snapshot.forEach(child => {
    console.log(child.val())
  })
})

So if you want to return both keys and values to res, you'll want to convert the snapshot into an array:

toolboxesRef.orderByChild('timestamp').once('value', snapshot => {
  let response = [];
  snapshot.forEach(child => {
    response.push({ key: child.key, value: child.val() });
  })
  res.json(response);
})

Upvotes: 1

Related Questions