How do i query a Firebase database for a nested property?

Hi i have a noSql db in firebase. I want to get the object where userId is 288 i'v tried many combinations but i cant figure out how its done. This is my code so far :

var refTest= database.ref('conversation')
var query = refTest
                .orderByChild('messages');

    query.on('value', function(data) {

 var a = data.val();
 console.log(a.messages.userId);
console.log(data.val());


});

This is a image of my "schema"

enter image description here

I'm obviously a noob when it comes to NoSQL. I do understand SQL All help is appreciated

Upvotes: 0

Views: 534

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 598837

You can order/filter on a nested value like this:

var refTest= database.ref('conversation')
var query = refTest.orderByChild('messages/userId').equalTo("288");

query.on('value', function(snapshot) {
  snapshot.forEach(function(child) {
    console.log(child.key);
    console.log(child.val());
  });
});

The forEach is needed, since there may be multiple child nodes with messages/userId equal to 288.

Upvotes: 1

Marius
Marius

Reputation: 1

The key named "messages" doesn't make sense in your schema. Because if you want to have another message under that conversation, then you wouldn't be able to add it with the same key name and you also couldn't add it under "messages" because it would overwrite the other one. My suggestion is to use the push() method for adding a new message. This way you uniquely identify each message.

Regarding your question, an easy to understand way of parsing your schema is this: you loop through each message of each conversation for finding the messages with userID.

refTest.on('value', function(data) {

    var conversations = data.val();
    for (conversation in conversations){
       for (message in conversation) {
          if (message.userId == 288) {
              // do whatever you need
              // and eventually return something to break the loops
          }
       }
    }

}

Of course, you can adapt it based on your needs

Upvotes: 0

Related Questions