Search code examples
node.jsfirebase-realtime-databasefirebase-admin

Firebase Cloud Function get inner child of child from list (nodeJs)


Trying to get all the 'Token' values from each child inside the Infos Child, when the database event onUpdate trigger ,but it seems I'm wrong any solutions? Table

   var allTokens = [];

    await admin.database().ref('/Roles/Livreurs').once("value", function (snapshot) {

        snapshot.forEach(function (childSnapShot) {

            childSnapShot.forEach(function (innerChild) {
                var token = innerChild.val().Token;
                allTokens.push(token);
            });
        });
    });

Solution

  • You only need forEach if you don't know the keys at a level in your JSON, in your case that only applies to the user IDs. For any level where you know the key, you can use child(thatkey) to get at that child snapshot.

    So I think you're looking for:

    let allTokens = await admin.database().ref('/Roles/Livreurs').once("value", function (snapshot) {
        var result = [];
        snapshot.forEach(function (userSnapShot) {
            var token = userSnapShot.child("Infos/Token").val();
            result.push(token);
        });
        return result;
    });
    

    And then use it as