Skip to content

Instantly share code, notes, and snippets.

@u007
Last active March 19, 2019 15:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save u007/d2cf78230afeee9d06220bb882022b56 to your computer and use it in GitHub Desktop.
Save u007/d2cf78230afeee9d06220bb882022b56 to your computer and use it in GitHub Desktop.
mongodb stitch function for database trigger to save updated_at and created_at
exports = function(changeEvent) {
console.log("changed", changeEvent.operationType, JSON.stringify(Object.keys(changeEvent)))
//allows replace and create
if(changeEvent.operationType == "update") {
let keys = Object.keys(changeEvent.updateDescription.updatedFields)
console.log("changed", JSON.stringify(Object.keys(changeEvent.updateDescription.updatedFields)))
if(keys.indexOf('created_at') > -1 || keys.indexOf('updated_at') > -1 || keys.length == 0) {
//changed fields contains created_at or updated_at
// on $set, it will trigger "update"
console.log("ignoring change")
return
}
}
let now = new Date();
now = new Date(now.toUTCString());
var docId = changeEvent.documentKey._id;
console.log("on", changeEvent.operationType, changeEvent.ns.coll, docId)
collection = context.services.get("c0").db("d1").collection(changeEvent.ns.coll);
if(changeEvent.operationType == "insert") {
collection.updateOne({ _id : docId }, { $set: { created_at : now, updated_at : now } } )
} else {
collection.updateOne({ _id : docId }, { $set: { updated_at : now } } )
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment