Skip to content

Instantly share code, notes, and snippets.

@u007 u007/source.js
Last active Mar 19, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.