prokawsar
prokawsar

Reputation: 170

Retrieve data by specific value in firebase

I am new to firebase. I am making an app in vue and firebase. Here is I have ref 'users' like this snap.

enter image description here

In text:

-L0PZ870WKlPC2BpRxbw email: "[email protected]" name: "Carol Howard" -L0P_xMlFVxOFuQ0yHne email: "[email protected]" name: "Alvin Boyd"

I want to get name where email I will provide. Need solution in JavaScript which needs to able run in vue app. A function like this would be appriciate

function(email){ // some code return name } How can I accomplish this?

Upvotes: 1

Views: 2459

Answers (1)

Cappittall
Cappittall

Reputation: 3441

Here bellow if you have a user email, then you can retrieve user name as follow;

getNameByEmail(email) {
        var db = firebase.database();
        var ref = db.ref('users').orderByChild('email').equalTo(email);
        ref.once('value', snapshot => {
           if (snapshot.exists()) {
               var name = snapshot.val();
               name = Object.values(name);
               name = name[0].name;
               console.log('User email : ' + email + ' User name: '+ name );
           } else {
              console.log('There is no user who has email like '+ email)
           }
    })

}

In case, if you are searching often users with emails, then better to define index for better performance set databse rules like;

{
  "rules": {
    ".read": true,
    ".write": "auth != null",
    "users": { ".indexOn": ["email"] }
  }
}

Upvotes: 3

Related Questions