Home > Software design >  Is Firestore onCreate trigger contains the latest data or only the data submitted during creation?
Is Firestore onCreate trigger contains the latest data or only the data submitted during creation?

Time:12-11

I have a commenting system that I need to keep track of number of comments. I am thinking to use the onCreate trigger to keep track of the comments count whenever a comment is created.

I understand that the onCreate trigger can be called multiple times, so, in order to make the function idempotent I am looking at the following implementation:


functions.firestore.document('users/{userId}/comments/{commentId}').onCreate(async (snap, context) => {
  const data = snap.data()

  if (data.counted) {
    return
  }

  db.doc(`commentCounter/${userId}`).update({
    value: admin.firestore.FieldValue.increment(1)
  })
  
  snap.ref.update({ counted: true })
}

Will this works? The main question is whether the data from snap reflects the current data in firestore, or the only data during the document creation. Thank you for your time.

CodePudding user response:

The onCreate function is trigger with the data that was created when the document was created. If there has been an update between when the document was created and when your Cloud Function runs, it will not be included in the snapshot that is passed to your code.

If you want the increment from your Cloud Function to be in addition to any increment that may have happened since document creation, then using an increment is the right solution.

On the other hand, if you want the document to be initialized by the Cloud Function and not have other writes before that, you'll probably want to use security rules to reject those early writes, for example based on a marker/flag field that he Cloud Function then writes.

  • Related