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!
Answer
where
userID
andtargetTimeStamp
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
})
})
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM