How to Auto Update a Timestamp on Upsert in Mongodb How to Auto Update a Timestamp on Upsert in Mongodb mongoose mongoose

How to Auto Update a Timestamp on Upsert in Mongodb


Mongoose middleware doesn't fire on update calls, so you'd need to do it yourself:

var expires = new Date();expires.setHours(expires.getHours() + 1);MyModel.update({...}, {$set: {expires: expires, ...}}, {upsert: true}, callback);

Also, I don't know your use case, but you should also look at Mongo's built-in support for expiring data from collections if that's what you're trying to do. See here.


Recent versions of Mongoose allow passing { timestamps: true } as an option when creating new models. This feature will automatically set createdAt and updatedAt. Here is the documentation.