Jonathan
Jonathan

Reputation: 73

How to Structure Firebase Realtime DB read request: Order by Key's Child

I have data stored in a firebase realtime database, in the following format.

users:
    -L5ZAb7r10_nqss7Ag:
        role: "user"
        email: "[email protected]"
        username: "King Arthur"
    -KL3Abnar7_nals8:
        role: "admin"
        email: "[email protected]"
        username: "Queen Ferdinand"

And in the database.rules.json I have:

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

On the front end I have a user giving their email, having been authenticated with Google OAuth, and I want to see if their email is a valid user, and if so return their role and username, otherwise throw an error. Right now I loop through the 'n' accounts and check each account's email. O(n) is obviously a really sucky runtime.

Not knowing what the user's key in the database is (the "-L5ZAb7r10_nqss7Ag" part), I want to be able to check for the given email in O(1) by searching the email in the indexed database. What I have in mind is something like the below. If this is posisble can someone point me to the riht documentation for the correct syntax?

firebase.database().ref(`/users/`).getIndexedValue($key/[email protected]).once('value').then(function(snap){
    if(snap == null) console.log("error);
    else{
       user = snap.val();
       console.log(user[role]);
       console.log(user[username]);
    }
}

I know the above won't work, .getIndexedValue() isn't real. What would be the correct syntax for this functionality? Is there someway to look for a specific indexed value (the email) that sits below an arbitrary partent (the -KL3Abnar7_nals8)?

Upvotes: 0

Views: 38

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598787

You're looking for orderByChild() and equalTo(). Something like this:

firebase.database()
  .ref('users')
  .orderByChild('email')
  .equalTo('[email protected]')
  .once('value').then(function(snapshot){
    if (snapshot.exists()) {
      snapshot.forEach(function(snap) {
       user = snap.val();
       console.log(user[role]);
       console.log(user[username]);
      })
    }
}

To learn more about Firebase Database queries, see the documentation on sorting and filtering data. I'd also recommend checking some previous questions on the topic.

Upvotes: 1

Related Questions