shaddles
shaddles

Reputation: 141

How can I get all the child nodes from a parent node in Firebase?

So I'm intending of retrieving a list of nodes from the parent node societies which will store the child node names, retrieved from this case being ALT5 , ASN11 , Foot15

Screenshot of firebase

The child node directly beneath sUsers is the uid of that user so it can be retrieved using var runUid = firebase.auth().currentUser.uid; so that the query can work with multiple users with different child nodes

EDIT : This needs to work on other nodes within sUsers that will have different child nodes under Societies

code so far, currently because there are 3 child nodes under societies it will log 3 null values, whereas I want the actual names of the child nodes stored

    firebase.auth().onAuthStateChanged(function(user){
   var userID = firebase.auth().currentUser.uid;
   var rootRef = firebase.database().ref('sUsers');
   var newRoot = rootRef.child(userID).child('Societies')
    newRoot.once('value', function(snapshot){
        snapshot.forEach(function(childs){
            var societies = childs.child('Societies').val();
            console.log(societies);

        });
    });
});

Upvotes: 3

Views: 5171

Answers (1)

balsick
balsick

Reputation: 1201

In the code you posted, the variable childs you're using in DataSnapshot.forEach is actually each child of the node 'Societies'. So this should work:

firebase.auth().onAuthStateChanged(function(user){
    var userID = firebase.auth().currentUser.uid;
    var rootRef = firebase.database().ref('sUsers');
    var newRoot = rootRef.child(userID).child('Societies');
    newRoot.once('value', function(snapshot){
        snapshot.forEach(function(_child){
            var society = _child.key;
            console.log(society);
        });
    });
});

Here you can see some documentation and some examples.

Upvotes: 5

Related Questions