skip to Main Content

I’m trying to migrate to Could Functions 2nd gen. Here is what I have tried:

import {
  onDocumentWritten,
  Change,
  FirestoreEvent
} from "firebase-functions/v2/firestore";

exports.myfunction = onDocumentWritten("users/{userId}", (event) => {
  console.log(event.data.after.data());
});

I following the docs but there is nothing mentioned about how to know what kind of event happened when using onDocumentWritten? Is it created, updated or deleted?

2

Answers


  1. You can test some part of the event to know the type of event

    exports.myfunction = onDocumentWritten("users/{userId}", (event) => {
      console.log(event.data.after.data());
        // If the document does not exist, it was deleted
        const document =  event.data.after.data();
    
        // If the document does not exist, it's a creation
        const previousValues =  event.data.before.data();
    
        // Else, it's an update.
    });
    
    Login or Signup to reply.
  2. I had written this code which uses the same concept as samthcodingman, so this is how it would look. As mentioned, for all three events.

    Javascript

    import {
        onDocumentWrite,
        Change,
        FirestoreEvent
    } from "firebase-functions/v2/firestore";
    
    exports.myfunction = onDocumentWrite("users/{userId}", (change,context) => {
        const newValue = change.after.data();
        const previousValue = change.before.data();
    
        if (!previousValue) {
            // This is a create operation
            console.log("Document created:", newValue);
        } else if (!newValue) {
            // This is a delete operation
            console.log("Document deleted:", previousValue);
        } else {
            // This is an update operation
            console.log("Document updated:", newValue);
        }
    });
    

    So, using the change object. If change.before is null, it’s a create. if change.after is null, it’s a delete. Otherwise, it’s an update operation.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search