update document attribute without triggering onUpdate() with cloud functions

Viewed 346

I would like to assign a new value to the document when previousValue has a certain value. I could execute firestore('collection').doc('id').update(newValue) but the trigger would fire again and be looped.

I would like to create a business rule when the document is changed and update that document object with a new value, but I don't want to call the onUpdate() function again.

export const onScheduleUpdated = functions.firestore
  .document('units/{unitId}/schedules/{scheduleId}')
  .onUpdate(async (change, context) => {

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

    if (!newValue) { return; }

    if (previousValue && previousValue.status === 'inAttendance'
      && newValue.status === 'answered') {

      const hour = moment();
      const hourSchedule = moment(newValue.endHour);

      if (hour.diff(hourSchedule, 'minutes') <= 59) {
        newValue.endHour = moment().toDate();
      }

      /**
       * If I do it will be in a correct loop? I would like to create business rules within 
       * this function to change the value of the document without triggering the trigger again.
       */
      await firestore.collection('units').doc(context.params.unitId)
      .collection('schedules').doc(context.params.scheduleId).update(newValue);

    }
  });

Is it possible to update the document by assigning a new value to a document attribute at the moment the onUpdate() function is triggered without triggering this trigger again?

0 Answers
Related