MongoDB / Mongoose timestamps not updating
Can try by modify your schema like:
var schema =new Schema({..},
{ timestamps: { createdAt: 'createdDate',updatedAt: 'updatedDate' }
});
for this schema timestmps will update on save()
, update()
and findOneAndUpdate()
. so no need schema.virtual('updated')...
Process-2
added createdDate
and updatedDate
with Date
type in your schema and update these date fields using schema plugin.
like:
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
SchemaPlugin = require('../helpers/schemaPlugin');
var schema =new Schema({..},
createdDate: {
type: Date,
default: Date.now
},
updatedDate: {
type: Date,
default: Date.now
}
});
schema.plugin(SchemaPlugin);
in schemaPlugin.js
file:
module.exports = function(schema) {
var updateTimestemps = function(next){
var self = this;
if(!self.createdAt) {
self.createdDate = new Date();
//or self.update({},{ $set: { createdDate : new Date(), updatedDate: new Date() } });
} else {
self.updatedDate= new Date();
//or self.update({},{ $set: {updatedDate: new Date() } });
}
next();
};
schema.
pre('save', updateTimestemps ).
pre('update', updateTimestemps ).
pre('findOneAndUpdate', updateTimestemps);
};
Stumbled upon the same thing, figured out that if the property updatedAt
is set on my object when I'm updating it with findOneAndUpdate()
(or update()
), it won't update it.
In my case, solved it by making sure updatedAt
isn't set before update:
delete thing.updatedAt;
Thing.findOneAndUpdate(
{ _id : thing._id },
thing,
function (err, result) {
…
Credit to Valeri Karpov for his answer on Github.