Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I trigger a firebase cloud function only when a field is updated?

I would like to trigger a cloud function only when a particular field of a firestore document is updated. I don't want to trigger it every time the document is updated regardless which field. Is it possible?

For example:

exports.onAvatarUpdated = functions.firestore.document('users/{userId}/avatarUrl')
  .onUpdate(change => { 
  // do something here
});
like image 807
Dewey Avatar asked Aug 27 '18 13:08

Dewey


2 Answers

Currently there are no triggers for a specific field. You can only trigger on any change to a document, and if you want to know if a particular field changed, you have to examine the change object to figure it out.

You can always file a feature request if you would like to be able to express a function that only pays attention to particular field.

like image 160
Doug Stevenson Avatar answered Nov 05 '22 23:11

Doug Stevenson


I will change Firebase native manual code from here:

exports.updateUser = functions.firestore
.document('users/{userId}')
.onUpdate((change, context) => {
  // Get an object representing the document
  // e.g. {'name': 'Marie', 'age': 66}
  const newValue = change.after.data();
  const newFieldValue = newValue.field;

  // ...or the previous value before this update
  const previousValue = change.before.data();
  const previousFieldValue = previousValue.field;


  if (previousFieldValue!== newFieldValue) 
       {      // perform desired operations ... }
});
like image 39
Liker777 Avatar answered Nov 06 '22 01:11

Liker777