Morad Edwar
Morad Edwar

Reputation: 1050

firebase query on the second/third level

I am using Javascript with Firebase and I want to make a query on a value exist on the second or the third level, My DB is like that :

Users :
        -KNwBd5cF6iY9dWh0eFd :
                name: "Jon Snow"
                phones:
                    phone1: "0123456789"
                    phone2: "0123456987"

And I want to make a query on the phone1 value, I am using orderByChild to query the DB for now and my code is :

var ref = firebase.database().ref("users");
ref.orderByChild("name").equalTo("Jon Snow").on("value", function(snapshot) {
    console.log(snapshot.val());
});

But I can only use it to query on the value of the first level of values but how to make another query on the second or third level.

Upvotes: 5

Views: 1988

Answers (1)

adolfosrs
adolfosrs

Reputation: 9389

Without knowing the phone id and considering your current database structure this wont be possible.

One workaround is to use the actual phone number as the key in /phones.

{ 
  users:
    userId:
       phones:
          0123456789: true
}

Then you will be able to retrieve it with:

ref.orderByChild("phones/"+phoneNumber).equalTo(true).once("value", function(snapshot) {
    console.log(snapshot.val());
});

Working jsFiddle.


This would be simple if you had the phoneId.

ref.orderByChild("phones/phone1").equalTo("0123456789").once("value", function(snapshot) {
    console.log(snapshot.val());
});

Since you don't, it turns to be a good example of how you should not be structuring a noSQL database.

noSQL databases are very flexible and its structure will depend pretty much on your application. So keep it in mind. If, for example, searching for a phoneNumber will be critical in your application and you want to have more data inside /phones/phoneNumber/ you should consider having a new separate branch to handle this in a more dedicated manner than you are doing now.

Upvotes: 3

Related Questions