Reputation: 3314
I have the follow single child data structure and want to retrieve an order list by child property rating
:
players: {
360368: {
name: "Joe, Blogs",
rating: 1853
},
400017: {
name: "Bob, Dylan",
rating: 2597,
},
430013: {
name: "James, Dean",
rating: 2152,
}
}
let ref = this.fb.ref('players');
ref.orderByChild("rating").limitToFirst(100).once("value", function(snapshot) {
console.log(snapshot.val());
});
The results returned appear to have no logical numeric order.
Finally, when I run the following query I get the results I expect (seeing ten players with a rating 2597):
let ref = this.fb.ref('players');
ref.orderByChild("rating").equal(2597).limitToFirst(10).once("value", function(snapshot) {
console.log(snapshot.val());
});
It appears that the data is being returned by object key. How can I ensure this is returned, ordered by rating
?!
Upvotes: 1
Views: 754
Reputation: 598740
When you request a value
event for a query, Firebase returns a snapshot that contains all children and information on their order. But when you request the val()
of that snapshot, the children are converted into a JOSN object and the ordering information is lost.
The solution is to use the snapshot to navigate the children and only convert to JSON once you've gotten them in the right order:
let ref = this.fb.ref('players');
ref.orderByChild("rating").equal(2597).limitToFirst(10).once("value", function(snapshot) {
snapshot.forEach(function(childSnapshot) {
console.log(childSnapshot.val());
});
});
Upvotes: 6