Reputation: 21
I want to use orderByChild on timestamp.
But it doesn't work well. They even sort by ascending or descending.
Here is the result :
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
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