aravk33
aravk33

Reputation: 489

Firebase - How to find the name of other children using a child?

In firebase, I'm trying to make a login system where a user can login using his/her username and password. However, as firebase authentication requires email id and password, I have another database where both the username and email id are stored under a parent(I'm not sure if parent is the right word though) as its children. The name of the parent is randomly generated.

When a user logs in, I need to go to this database and find out the email address whose "brother" is the username entered. I tried keeping the username as the parent's name, but then for specific reasons, I had to change it back to this structure. So how do I accomplish this with the new structure(where both email and username are children)? Here is the function which I used when the username was the parent, to find the email id.

function getEmail(username) {
    var usersRef = database.ref(username).child("email");
    usersRef.on("value", function(snapshot) {
        email = snapshot.val();
    }, function (errorObject) {
        console.log("The read failed: " + errorObject.code);
    });
}

EDIT: Here is the JSON:

{
  "user 1" : {
    "email" : "[email protected]",
    "username" : "Test1"
  },
  "user 2" : {
    "email" : "[email protected]",
    "username" : "Test2"
  }
}

Upvotes: 0

Views: 404

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

You'll need a query to get the result you want:

var usersRef = database.ref().orderByChild("username").equalTo(username);
usersRef.once("child_added", function(snapshot) {
    email = snapshot.val().email;
}, function (errorObject) {
    console.log("The read failed: " + errorObject.code);
});

My code uses once("child_added" since you're probably only interested in the first matching child.

Alternatively, you can modify you data structure to use the user names as the key:

"emailsByUsernames": {
  "Test1" : "[email protected]",
  "Test2" : "[email protected]",
}

Then you can directly lookup the email like this:

var usersRef = database.ref(emailsByUsernames).child(username);
usersRef.on("value", function(snapshot) {
    email = snapshot.val();
}, function (errorObject) {
    console.log("The read failed: " + errorObject.code);
});

Upvotes: 0

Related Questions