I have the following functions that listens to an onWrite event for a database trigger like so:
exports.sendNotifications = functions.database.ref('/events/{eventId}/registered') .onWrite(event => { ... });
The above function is called regardless whether the node is deleted or added. How do I check if the onWrite event is a 'delete' event for that particular node, or a 'add' event, such that this function only gets called when it is a 'add' event.
If you want to only trigger this function for an add event, the onCreate()
trigger would be the way to go.
However, you can also detect if it is an add event inside your onWrite()
using the before
and after
properties of the Change
object:
exports.sendNotifications = functions.database.ref('/events/{eventId}/registered') .onWrite((change, context) => { if (change.before.exists()) { //update event return null; } else if (!change.after.exists()) { //delete event return null; } else { //add event //do stuff } });
Find more details in the documentation:
https://firebase.google.com/docs/functions/database-events#handle_event_data
The event
that is passed into the function contains both the previous data and the new data for the location that triggered the function. With these two pieces of information, you can deduct whether it was a new write, an update, or a delete.
From the Firebase documentation for database functions:
exports.makeUppercase = functions.database.ref('/messages/{pushId}/original') .onWrite(event => { // Only edit data when it is first created. if (event.data.previous.exists()) { return; } // Exit when the data is deleted. if (!event.data.exists()) { return; }
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