Erick Maynard
Erick Maynard

Reputation: 801

JavaScript Firebase: Query Snapshot Always Null

No matter what I do I can't seem to figure out a way to access the child "onSite", which shows as being there when I log snapshot.val(), but I cannot figure out how to access it.

Code:

firebase.database().ref().child("users").orderByChild('facebook_id').equalTo(fbID).once("value").then(function(snapshot) {
    console.log(snapshot.val());
    console.log(snapshot.child("onSite").val());
});

Here is the response: enter image description here

It shouldn't be null, it should be false. I can't do child("4mUUjF...").child("onSite").val() because I don't know what the ID is before the query. Using an each loop doesn't work, it only loops through the first level, which is the ID.

Upvotes: 0

Views: 714

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

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 code needs to handle the list, by using Snapshot.forEach():

firebase.database().ref().child("users").orderByChild('facebook_id').equalTo(fbID)
.once("value").then(function(result) {
    result.forEach(function(snapshot) {
        console.log(snapshot.val());
        console.log(snapshot.child("onSite").val());
    });
});

Upvotes: 2

Joe Lloyd
Joe Lloyd

Reputation: 22323

Use the key of the object

Get the snapshot val and then find the key with the Object.keys method. This will allow you to then get inside the snap. Once there it's a simple matter of accessing the values like any other object.

firebase.database().ref().child("users").orderByChild('facebook_id').equalTo(fbID).once("value").then(function(snapshot) {
    let snap = snapshot.val();
    let key = Object.keys(snap)[0]
    console.log(snap[key].onSite);
})

Upvotes: 4

Related Questions