Hey @Tyler_Kaye , Thank you for the quick reply.
edited: I didn’t have the trigger active, oops. Sorry!
issue:
On insert it triggers the function 3 times. Here is my function:
exports = function(changeEvent) {
const dbName = changeEvent.ns.db;
const collectionName = changeEvent.ns.coll;
const collection = context.services.get('mongodb-atlas').db(dbName).collection(collectionName);
const currentDate = new Date();
// Check the operation type
if (changeEvent.operationType === 'insert') {
// If it's an insert, set both createdAt and updatedAt
collection.updateOne(
{ _id: changeEvent.documentKey._id },
{
$set: {
createdAt: currentDate,
updatedAt: currentDate
}
}
)
.then(result => {
console.log(`Inserted document in ${collectionName} collection with createdAt and updatedAt fields.`);
})
.catch(error => {
console.error('Error setting createdAt and updatedAt on insert:', error);
});
} else if (changeEvent.operationType === 'update') {
// If it's an update, only set updatedAt
collection.updateOne(
{ _id: changeEvent.documentKey._id },
{
$set: {
updatedAt: currentDate
}
}
)
.then(result => {
console.log(`Updated document in ${collectionName} collection with updatedAt field.`);
})
.catch(error => {
console.error('Error setting updatedAt on update:', error);
});
}
return;
};
