问题
I want to get the position of an item in the database, along with the data.
.ref("users")
.orderByChild("email")
.equalTo(myEmail)
.once("value", snapshot => {
console.log("Database Position", ???? )
}
Is there a value in the snapshot that I could use that indicates the position in the database (after ordering by email)? I don't want to do this on the client side since I have >1k users
回答1:
The Firebase Realtime Database does not track the position of nodes in their parents, nor does it return such a position in query results. This means the only way to determine the position of a child within a set of child nodes, is to retrieve all child nodes before the one you're looking for.
.ref("users")
.orderByChild("email")
.endAt(myEmail)
.once("value", snapshot => {
var index = 0;
snapshot.forEach(function(childNode) {
if (childNode.child("email").val() === myEmail) {
console.log("Database Position", index);
}
else {
index = index + 1;
}
});
}
Since you commented that you're trying to create a leaderboard, see:
- Leaderboard ranking with Firebase
- Unity - Firebase realtime database - Get my rank in leaderboard
- Getting rank of user from firebase database in android
来源:https://stackoverflow.com/questions/55318674/how-to-get-the-position-of-an-item-in-the-realtime-database