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.