0

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

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
gvon79
  • 642
  • 3
  • 9
  • 18
  • Answer below. Since this may indeed not work for you, you might want to explain what you're trying to accomplish here. As it stands your question reads like a [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem), and if we know the actual goal we may be able to come up with an alternative approach. – Frank van Puffelen Mar 23 '19 at 23:24

1 Answers1

2

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:

I'd also recommend checking out Dan's answer on Leaderboard ranking with Firebase, which also shows ways to store each player's rankings. While that post is about Firestore, the same principles and considerations apply when implementing a leaderboard on Firebase's Realtime Database.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thanks Frank, this is unfortunate. I have a list of >1k users that are ranked (by 'Score'). I was hoping I could use the position in the database to use as their rank. I suppose the best method would be to run a firebase function once per day to update a rank field. – gvon79 Mar 24 '19 at 13:37
  • I added links to some previous answer about leaderboards and ranking. – Frank van Puffelen Mar 24 '19 at 14:21