How to set update timestamp in upsert operation in Mongoose? How to set update timestamp in upsert operation in Mongoose? mongoose mongoose

How to set update timestamp in upsert operation in Mongoose?


You can't do it automatically. You can do it using $set: { timestamp: Date.now() } on upsert.

There is a closed issue in mongoose bugtracker discussing this, here: defaults are ignored on upsert

A little late, but hope that helps someone!


you could use a pre save hook, there are a number of flags like .isNew or .isModified you can use.

self.schema.pre('save', function (next) {  if (this.isNew) {    this.updated = Date.now();  }  return next();}

For the creation date a timestamp can be extracted from the ObjectId


for insert

db.test.insert({ts:new Date()})

for upsert

db.test.update({"_id" : ObjectId("540815fa802a63ddca867bc0")},{$set:{ts:new Date()}},{upsert:1})