4
votes

I have a document collection called schools for which we have kept fields called createdAt and updatedAt. I'm updating these fields using firestore cloud trigger functions in onCreate and onUpdate triggeres respectively.

The problem I'm facing here is, these field updates will call onUpdate trigger again unnecessarily. For these to handle, I've written an additional function called skipOnUpdateTrigger

const excludeFields = ["createdAt", "UpdatedAt"]

shouldSkipOnUpdateTrigger = function(docDataOld, docDataNew, excludeFields){
    for(let i of excludeFields){
        if (docDataOld[i] !== docDataNew[i])
            return true;
 }
    return false;
}

Is there a better way I can handle this situation to avoid those extra triggers?

2

2 Answers

3
votes

The simplest way I've found is to prevent the need for Cloud Functions altogether, and let the client include the lastUpdated value in each write with a server-side timestamp.

You can enforce this in security rules, by checking:

allow update: if request.resource.data.lastUpdated = request.time
1
votes

I think you have the right idea. You have to compare the before and after snapshots to make sure that an update happened where you actually want to modify the timestamp. There is no way to know how the change happened (it could be client or server), so you have to look at the data itself.