Ad

How To Filter And Retrieve Nested Child In Firebase Realtime Database?

This is a simplified version of the DB structure that I'm working with:

  "user" : {
    "nhbAQ9p8BrMoAIbJNKvLlXTdiNz2" : {
      "log" : {
        "-LhMVugmjmIdqwrJSURp" : {
          "a" : 25120,
          "timeStamp" : 1560312000000,
        },
        "-Lh_Z9GsJJvlMOpVV9jU" : {
          "a" : 19033,
          "timeStamp" : 1564718400000,
        }
      }
    }
  }

I'm having issues filtering and retrieving the value of "a" with a given user id (e.g. nhbAQ9p8BrMoAIbJNKvLlXTdiNz2) and timeStamp (e.g.1560312000000).

I've tried combinations of orderByChild(), equalTo(), and adding a once() listener to do the task but they've only returned null so far.

The code that I have:

firebase.database().ref('user/' + userID + + '/log').orderByChild('timeStamp').equalTo(targetTimeStamp).once('value').then(function(snapshot){
    let userLog = snapshot.val().a
})

where userID is a string and targetTimeStamp is a number.

I checked the doc and a post about orderByChild() but I'm still not sure what is causing it to return null.

This is my first time posting a question, please comment if there's anyway I can make this clearer and any help is much appreciated!

Ad

Answer

where userID and targetTimeStamp are both strings.

That is the reason nothing is returned. In the database the values of the timeStamp property is a number, and comparing a number to a string never returns a match.

To make the query work, convert the string to a number:

...equalTo(parseInt(targetTimeStamp)).once(...

Aside from that a query against the Firebase Database may potentially have 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.

So you need to handle that case too:

firebase.database().ref('user/' + userID + + '/log').orderByChild('timeStamp').equalTo(targetTimeStamp).once('value').then(function(results){
    results.forEach(function(snapshot) {
        let userLog = snapshot.val().a
    })
})
Ad
source: stackoverflow.com
Ad