Cloud function for firestore onWrite

Viewed 247

When I update or delete my document via firebase console my function triggered but when I log the field context.eventType I'm getting google.firestore.document.write instead of google.firestore.document.delete or google.firestore.document.update

Any clue please ?

Code:

exports.useTest = functions.firestore
    .document("users/{userId}")
    .onWrite(async (handle, context) => {
    console.log("before", handle.before.data());
    console.log("after", handle.after.data());
    console.log("eventType", context.eventType);
});
1 Answers

According to this documentation, your Firestore functions will trigger the onWrite since it is triggered whether onCreate, onUpdate or onDelete is triggered. Regardless of the trigger, the onWrite will be shown.

There's also a guide to trigger a function for all changes to a document that you can follow:

exports.modifyUser = functions.firestore
    .document('users/{userID}')
    .onWrite((change, context) => {
      // Get an object with the current document value.
      // If the document does not exist, it has been deleted.
      const document = change.after.data();

      // Get an object with the previous document value (for update or delete)
      const oldDocument = change.before.data();

      // perform desired operations ...
    });

For further reference, you can refer to these documentations:

  1. Trigger a function when a new document is created
  2. Trigger a function when a document is updated
  3. Trigger a function when a document is deleted
Related