0

I am trying to get the child value of sender if its equal to the current logged in user.. but I was unable to get the same.

The JSON of the database is below:-

{
  "requests" : {
    "YJ5qTg2uuqQeicsWCTCNQMv4OwL2" : {
      "-Lecn9gN5puugx5z-PKX" : {
        "sender" : "0XWmi1Izr6XHYvqxamfNHDONSVA2",
        "status" : "Pending"
      }
    }
  }

}

This is what I have tried but I am always getting null.

this.firebase.database().ref('/requests').orderByChild('sender').equalTo(firebase.auth().currentUser.uid).on('value',(snapshot) =>
    {
      console.log(snapshot.val());
    })

But every time I am getting null.

I did understand that I should provide the child address to reach to the grand child.

this.firebase.database().ref('/requests').orderByChild('-Lecn9gN5puugx5z-PKX/status').equalTo('Pending').on('value',(snapshot) =>
    {
      console.log(snapshot.val());
    })

If I am explicitly providing the child address then I am getting the value needed.

Abhishek
  • 528
  • 6
  • 17

1 Answers1

0

When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.

Your callback will need to handle that list by looping of the child nodes of the result with forEach. So something like:

this.firebase.database().ref('/requests')
.orderByChild('-Lecn9gN5puugx5z-PKX/status').equalTo('Pending').on('value',(snapshot) => {
  snapshot.forEach((child) => {
    console.log(child.key+': '+child.val());
  })
})
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • But how to get the grand child here status directly without having any knowledge about the child here -Lecn9gN5puugx5z-PKX – Abhishek May 12 '19 at 01:52
  • Ah wait, you're two dynamic levels deep. That sort of query is not possible. Firebase can only query child properties at a known path under each immediately child. See my answer here: https://stackoverflow.com/questions/27207059/firebase-query-double-nested – Frank van Puffelen May 12 '19 at 03:01
  • Ohk thanks, can firestore help me? – Abhishek May 12 '19 at 08:31
  • Firestore just launched collection group queries, where you can query across all collections with a specific name. If that will allow the query you want is hard to say for me, but you might want to check it out. – Frank van Puffelen May 12 '19 at 14:23
  • Sure thanks for ur help. – Abhishek May 13 '19 at 15:04