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!
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With