Last active
March 19, 2019 15:07
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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