Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FIrestore document onUpdate: trigger only for specific fields

in my cloud function I have next unction:

export const collectionOnUpdate = functions.firestore.document('cards/{id}').onUpdate(async (change, context) => {
  await updateDocumentInAlgolia(change);
});

And this function is triggered each time, when any fields of document was edited. But I want to run it only when one of specific fields was changed (in this case, for example: title, category) and not when any of other.

How can I do this?

like image 413
Vladimir Humeniuk Avatar asked Jul 26 '26 20:07

Vladimir Humeniuk


1 Answers

firebase firstore cloud functions are works based on the basis of changes to the documents,not based on the fields of a document.

So if you want to check whether some fields have any change,you have to check manually

exports.updateUser = functions.firestore
.document('users/{userId}')
.onUpdate((change, context) => {

  // ...the new value after this update
  const newValue = change.after.data()||{};

  // ...the previous value before this update
  const previousValue = change.before.data()||{};

  // access a particular field as you would any JS property

  //The value after an update operation
  const new_name = newValue.name;

  // the value before an update operation
  const old_name = previousValue.name;

  if(new_name!==old_name){
   //There must be some changes
   // perform desired operations ...
  }else{
  //No changes to the field called `name`
  // perform desired operations ...
  }


});
like image 182
pepe Avatar answered Jul 28 '26 13:07

pepe