This is a story about investigating how to use only createdAt with Mongoose’s timestamp options, but finding that I had to implement it in pre hooks myself.
First, at the time of Mongoose version 4.8.5, from reading the source code, options.timestamps doesn’t have an option to use only either createdAt or updatedAt.
Below is a partial excerpt from Mongoose’s source code:
/** * Setup updatedAt and createdAt timestamps to documents if enabled * * @param {Boolean|Object} timestamps timestamps options * @api private */ Schema.prototype.setupTimestamp = function(timestamps) { if (timestamps) { var createdAt = timestamps.createdAt || 'createdAt'; var updatedAt = timestamps.updatedAt || 'updatedAt'; // ... } };
So here’s sample code that adds options.timestamps-like hooks to .pre(“save”), .pre(“findOneAndUpdate”), .pre(“update”), etc.
var yourSchema = new Schema({
createdAt: {
type: Date
}
});
yourSchema.pre("save", function(next) {
var now = new Date;
if (this.isNew) {
this.createdAt = now;
}
return next();
});
yourSchema.pre("findOneAndUpdate", function(next) {
var now = new Date;
this.findOneAndUpdate({}, {
$setOnInsert: {
createdAt: now
}
});
return next();
});
yourSchema.pre("update", function(next) {
var now = new Date;
this.update({}, {
$setOnInsert: {
createdAt: now
}
});
return next();
});
Finally, as a side note, there’s an issue about removing timestamp options, so checking that, it might be removed in version 4.11 milestone.
That’s all from the Gemba.