How to call the $firebaseArray in the cloud function of firebase

So in my angular JS web app, I have a function that calls on a node in the firebase database called orderedPlayers and returns it as an array as follows:

$firebaseArray(orderedPlayers)
        .$loaded(function(loadedPlayers) {
  // function in here
        });

When attempting to do something similar in the cloud function I am experiencing problems. Is there a way to return the the players node as an array?

I know i can access the database as follows:

admin.database().ref('orderedPlayers');

but the $firebaseArray doesnt work.

2 answers

  • answered 2018-03-13 21:47 Drei

    To the best of my knowledge cloudfunctions does not include firebaseArray. You can instead just make the players children into an array.

    so:

    let yourArray = [];
    admin.database().ref('orderedPlayers').once('value').then(snap => {
        snap.forEach(childSnap => {
            yourArray.push(childSnap));
        });
    });
    

    or you can use the children:

    let yourArray = [];
    admin.database().ref('orderedPlayers').on('child_added',snap => {
        yourArray.push(snap);
    });
    

    *on('child_added') will always be called at least once so it removes the need to loop over the children.

    If you want to query the database by a specific value you just add something like orderByChild('order') after the ref and before calling once or on

  • answered 2018-03-13 22:05 Tristan

    These docs can help: https://firebase.google.com/docs/database/admin/retrieve-data

    snapshot.val() will return an object that can be referenced as a key-value array. In your case:

    admin.database().ref('orderedPlayers').on("value", function(snapshot) {
      var loadedPlayers = snapshot.val();
      //access your players here
    }, function (errorObject) {
      console.log("The read failed: " + errorObject.code);
    });