How to get the position of an item in the realtime database

谁说胖子不能爱 提交于 2019-12-25 01:25:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!