Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to look for a specific value in a DataSnapshot with Firebase Cloud Functions

I'm trying to make a cloud function that will trigger on HTTP request (which is sent on a timer), that will remove all childs with a specific value.

The database node looks like this:

activities
    4GI1QXUJG0MeQ8Bq19WOdCQFo9r1 //uid
        activity: "hammer"
        id: some ID
        note: "some note"
        timestamp: some timeintervalsince1970
    7IDUiufhiws8939hdfIUHiuhwdi5
        etc....

I want to look through all the activities, and if the activity value is "hammer", I want to remove the child.

This is what I have so far

exports.deleteHammerNotifications = functions.https.onRequest((req, res) => {

    admin.database().ref('activities').once('value', (snapshot) => {

        console.log(snapshot.val())

    });
});

which prints:

{ 
    '4GI1QXUJG0MeQ8Bq19WOdCQFo9r1': 
      { activity: 'nn',
        id: '4GI1QXUJG0MeQ8Bq19WOdCQFo9r1',
        note: 'Blank note...',
        timestamp: 1498032472 },
     M6xQU5XWTEVbSqBnR3HBAEhA9hI3: 
      { activity: 'hammer',
      id: 'M6xQU5XWTEVbSqBnR3HBAEhA9hI3',
      note: 'some note here...',
      timestamp: 1497973839 },
}

My problem is I don't know how to cycle through the DataSnapshot and look for all the childs that has the activity: "hammer" value. I have done similar function in my xcode project with arrays, but I don't know how to do it with JavaScript.

Any help is appreciated!

like image 572
Elhoej Avatar asked Jun 25 '17 08:06

Elhoej


1 Answers

To cycle through the matching child nodes, use snapshot.forEach():

exports.deleteHammerNotifications = functions.https.onRequest((req, res) => {
    admin.database().ref('activities').once('value', (snapshot) => {
      snapshot.forEach((childSnapshot) => {
        console.log(childSnapshot.val())
      });
    });
});

But you're still missing a query here to select the correct nodes. Without such a query you might as well call admin.database().ref('activities').remove().

To most efficiently delete a number of items from the database and write a single response back to the user, use this function (which I modified from something I needed recently):

exports.cleanup = functions.https.onRequest((req, res) => {
  var query = admin.database().ref("activities").orderByChild("activity").equalTo("hammer");
  query.once("value").then((snapshot) => {
    console.log("cleanup: "+snapshot.numChildren()+" activities");
    var updates = {};
    snapshot.forEach((child) => {
      updates["activities/"+child.key] = null;
    });
    admin.database().ref().update(updates).then(() => {
      res.status(200).send(snapshot.numChildren()+" activities deleted");
    }).catch((error) => {
      res.status(500).send(error);
    })
  });
});

Learn more:

  • Firebase documentation on querying
  • Firebase blog post on multi-location updates
like image 105
Frank van Puffelen Avatar answered Oct 26 '22 22:10

Frank van Puffelen