Populate created_at and modified_at properties using triggers

hi.

can i populate created_at and modified_at properties using triggers?

im tring something like this:

exports = function(changeEvent) {
  const collection = context.services.get("mongodb-atlas").db("db").collection("appointment");
  const doc = collection.findOne({ _id: changeEvent.documentKey._id });

  const strDate = new Date().toISOString();

  if (changeEvent.operationType == "insert") {
    changeEvent.fullDocument.created_at = strDate;
  }

  changeEvent.fullDocument.modified_at = strDate;


  return changeEvent;
}

any idea?

Hi @Bob_Dylan, welcome to the community forum!

You’re on the right track!

Rather than returning the updated document, you need to update the database from within your function (you can use $set to update or add the new timestamp.

One thing to watch out for is cascading triggers. When you add or update the timestamp in this document, the trigger will fire again (and again, and again,…). You could perform a check in the function to stop this (e.g., check that the current last-updated timestamp is more than 30 seconds older than the current time),

1 Like

There is my trigger function :slight_smile:

Thanks, Andrew.

exports = function(changeEvent) {
  const collection = context.services.get('mongodb-atlas').db('db').collection('appointment');
  const date = new Date();
  
  // hack cascading triggers
  if (
    changeEvent.operationType == 'update'
    && (
      changeEvent.updateDescription.removedFields.indexOf("modified_at") < 0
      || (
        changeEvent.updateDescription.updatedFields.modified_at
        && (date.getTime() - changeEvent.updateDescription.updatedFields.modified_at.getTime()) / 1000 < 10
      )
    )
  ) {
    return;
  }

  const objectUpdate = {
    modified_at: date
  };
    
  if (changeEvent.operationType == 'insert') {
    objectUpdate.created_at = date;
  }

  collection
    .updateOne(
      {
        _id: changeEvent.documentKey._id
      },
      {
        $set: objectUpdate
      }
    )
    .catch(function (error) {
      console.error(error);
    }
  );

  return;
};