Reputation: 127024
Let us imagine that this is my JSON data
values: {
a: {
randomValue: "set",
sorter: 1
},
b: {
randomValue: "hat",
sorter: 2
}
}
I can retrieve data from my database with the admin database (from Cloud Functions) like this
admin.database().ref('values/a').once('value').then(snapshot => {
console.log(snapshot.val().randomValue + ' .. ' + snapshot.val().sorter);
});
Output will be set .. 1
.
As soon as I attach a query to my request it stops working, i.e. it does not work like mentioned in the documentation.
There they can clearly access snapshot.val().height
with a query.
Although when I do my query like this
admin.database().ref('values').orderByChild('sorter').equalTo(1).once('value').then(snapshot => {
console.log(snapshot.val());
console.log(snapshot.val().randomValue + ' .. ' + snapshot.val().sorter);
console.log(snapshot.child('randomValue').val() + ' .. ' + snapshot.child('sorter').val());
}
The output will suprisingly be the following
a: {
randomValue: "set",
sorter: 1
}
undefined .. undefined
null .. null
So snapshot.val()
does give me my full data, but not a single way of accessing will give me any data, just undefined
or null
! Why is this the case?
Upvotes: 0
Views: 1426
Reputation: 7438
I believe you need to access the fields as snapshot.val().a.randomValue
in this case. Note that you're running the query against the values
node, and not the values/a
node. Therefore your result contains the a
property.
Update
When you run the query against the values
node, and subscribe to the value
event (which is what once()
method does internally), you get the full value (parent key + child) of the query. To get only the child, you need subscribe to a child event. This is what the samples in the documentation do. For instance:
admin.database().ref('values').orderByChild('sorter').equalTo(1).once('child_added').then(snapshot => {
console.log(snapshot.val());
console.log(snapshot.val().randomValue + ' .. ' + snapshot.val().sorter);
console.log(snapshot.child('randomValue').val() + ' .. ' + snapshot.child('sorter').val());
});
will yield the output you're trying to get:
{ randomValue: 'set', sorter: 1 }
set .. 1
set .. 1
Upvotes: 3