How to use triggers to update a document on insert

I am trying to make some triggers when insert or update some docuement in my collection but here i found a problem or i am doing something wrong…
when i create a function that updates the document it still running because i call again the update function, so this make a loop for update the date, is there any way to just update my document once after or before insert/update the document?

    exports = function(changeEvent) {
const collection = context.services.get('mycluster').db("mydb").collection("mycollection");
collection
    .updateOne(
      { _id: changeEvent.documentKey._id },
      { $set: { updatedDate: new Date() } }
    )
    .catch(err => console.error(`Failed to add updatedDate: ${err}`));

  return;
};

Hi Miguel!

At a high level, you’ll want to add logic to the match expression of your Trigger or within your Trigger’s function. Some approaches that might work –

  1. Using the match expression within your Trigger to avoid firing if updateDate has been updated (assuming other aspects of your application don’t use this field).
  2. Adding a new field with the last time a trigger updated, setting this within the Trigger logic, and filtering events where that field is updated.

Hope that helps!
Drew

1 Like