JavaScript Firebase: Query Snapshot Always Null

后端 未结 2 1632
無奈伤痛
無奈伤痛 2020-12-22 10:14

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 ac

相关标签:
2条回答
  • 2020-12-22 10:29

    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);
    })
    
    0 讨论(0)
  • 2020-12-22 10:48

    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());
        });
    });
    
    0 讨论(0)
提交回复
热议问题