Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make an action triggered only if a field is changed using onUpdate trigger Firestore cloud function?

There is a field in my event document called title which contains a boolean value. I have set onUpdate firestore trigger in my document. I want if my title is updated then I will do some action. but if other fields is updated then I will not perform any action at all. how to do that ?

I am okay if the function below is invoked every time there is an update on the document, but I want only do some further action only if the title is updated

exports.dbEventsOnUpdate = functions.firestore
.document('events/{eventId}').onUpdate(async (change,context) => {

        try {        
            const eventID = context.params.eventId

            if (titleIsUpdated) {
               return db.doc(``).set(newData)
            } else {
               // do nothing here
               return null
            }

        } catch(error) {
            console.log(error)
            return null
        }

    })
like image 676
Agung Laksana Avatar asked Jan 18 '26 08:01

Agung Laksana


1 Answers

Currently, Firestore Cloud Functions cannot be triggered based on a field update. It's only triggered when a document is updated.

You can actually check if the title was updated using the following code:

const newValue = change.after.data();
const previousValue = change.before.data();

const titleIsUpdated = newValue.title !== previousValue.title;

But keep in mind that your function will always be triggered when a field is changed in that document. And this might incur more costs, since Cloud Functions charge based on functions invocations. (See pricing)

like image 170
Rosário Pereira Fernandes Avatar answered Jan 20 '26 22:01

Rosário Pereira Fernandes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!