Home > OS >  Get Key Value Given Other Key Value in FireBase
Get Key Value Given Other Key Value in FireBase

Time:02-22

I am trying to find a way to find the value of the id given the email.

For example, If I had [email protected], It would give me the ID 108454568498950432898.

All emails are unique and there will be no repetition of emails.

This is my user tree:

enter image description here

Note: In the image it says email2 instead of [email protected]. Ignore this

Here's my code so far: (Code won't run obviously but it's easier to enter code using the embed)

var users;
var givenEmail = "[email protected]";
var neededID;

var dataRef = firebase.database().ref('users');
dataRef.on('value', (snapshot) => {
    const data = snapshot.val();
    users = data;
});

var usersArray = Object.keys(users);

for(i = 0; i < usersArray.length; i  ) {
    if(users[i].email == givenEmail) {
        neededID = i;
        break;
    }
}

CodePudding user response:

Well, I think you are almost there.

users[i].email

you can retrieve the email using this method, and similarly you can do it with id too

users[i].id

Please note that you wanted to find [email protected] but your firebase only have email2

Maybe you would want to change that

CodePudding user response:

I recommend using a query to perform the filtering on the server, instead of downloading the entire users node and filtering in your application code as you now do.

var givenEmail = "[email protected]";

var dataRef = firebase.database().ref('users');
var query = dataRef.orderByChild('email').equalTo(givenEmail);
dataRef.once('value', (snapshot) => {
    snapshot.forEach((userSnapshot) => {
        console.log(userSnapshot.val().id);
    });
});
  • Related