FRestore文档onUpdate:仅针对特定字段触发

Vla*_*iuk 2 firebase google-cloud-functions google-cloud-firestore

在我的云功能中,我有下一个功能:

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

每次编辑文档的任何字段时都会触发此功能。但我只想在特定字段之一更改时运行它(在本例中,例如:title, category),而不是在任何其他字段更改时运行它。

我怎样才能做到这一点?

pep*_*epe 9

firebase firstorecloud functions是基于文档更改的工作,而不是基于文档的字段。

所以如果你想检查某些字段是否有变化,你必须手动检查

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 ...
  }


});
Run Code Online (Sandbox Code Playgroud)