Alexandru Pufan
Alexandru Pufan

Reputation: 1912

Get unique id of specific element in Firebase

I have my Firebase database structured like this:

{
  "userProfile" : {
     "X0u2SEFfYEeVmdw4TXl58ou2eYy1" : {
        "email" : "[email protected]",
         "name" : "Jane"
      },
      "cliv7hQ4FsWKTtYksPDXcdDafdi2" : {
         "email" : "[email protected]",
          "name" : "John Doe",
       }
    }
}

I'm trying to get the unique id of the element that matches query criteria, for example the key of the element with email equal to [email protected].

I'm doing this by using:

firebase.database().ref('/userProfile').orderByChild('email').equalTo(email).once( 'value', data => {
    let user = data.val();
});

This returns me the entire object with that email, but I only want its unique id ("cliv7hQ4FsWKTtYksPDXcdDafdi2" in this case). What's the best way to achieve this?

Upvotes: 1

Views: 3470

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.

So:

var query = firebase.database().ref('/userProfile').orderByChild('email').equalTo(email);
query.once( 'value', data => {
    data.forEach(userSnapshot => {
        let user = userSnapshot.val();
        let key = userSnapshot.key;
    });
});

Upvotes: 3

Related Questions