title: Firestore + cloud function: How to tell if it's a create, update, or delete event
body: <p>I want to write a Firebase cloud function that is triggered by a Firestore write event. Inside of the function, I have to know if the write is actually a create, update, or delete function. The logic is slightly different, but I don't want to copy and paste three different event handlers. How can I tell which event type it is?</p>
  
  <p>The cloud documentation reads very confusing to me.</p>
  
  <p>The documentation for Event says that in the case of FireStore, the event is actually a DeltaDocumentSnapshot.</p>
  
  <p><a href="https://firebase.google.com/docs/reference/functions/functions.Event" rel="noreferrer">https://firebase.google.com/docs/reference/functions/functions.Event</a></p>
  
  <p>The documentation for DeltaDocumentSnapshot suggests that the class has no information about the event itself (e.g. indication of create, update, or delete), but only the target document:</p>
  
  <p><a href="https://firebase.google.com/docs/reference/functions/functions.firestore.DeltaDocumentSnapshot" rel="noreferrer">https://firebase.google.com/docs/reference/functions/functions.firestore.DeltaDocumentSnapshot</a></p>
  
  <p>I found samples, where the author seemed to infer create/update/delete by checking if the current or previous document exists. I've tried that but I get an error.</p>
  
  <p><a href="https://github.com/firebase/functions-samples/blob/master/child-count/functions/index.js#L30" rel="noreferrer">https://github.com/firebase/functions-samples/blob/master/child-count/functions/index.js#L30</a></p>
  
  <p>Here is what I've tried:</p>
  
  <pre><code>exports.updateLikeCount = functions.firestore
  .document('likes/{likeId}').onWrite((event) =&gt; {
      if (event.data.data().exists()) {
        // Looks like the document still exists. It must be an update or create.
      }
  
      if (event.data.previous.data().exists()) {
        // Looks like the document existed before. It must be an update or delete.
      }
  </code></pre>
  
  <p>That code fails with this error:</p>
  
  <pre><code>TypeError: event.data.exists is not a function
  </code></pre>