I am trying to update the automatically added createdAt date on a record to right now.
Here the code I am using:
Document.findOneAndUpdate({_id: docId}, {createdAt: new Date()}, function(err, updated) {});
It works on my dev environment, but not the server. It does not return an error, but does not update the record, just returns the unchanged record.
I tried formatting it with new Date().toISOnew Date().toISOString() or .toGMTString() but both still only work on the dev environment. Both have node 6.10, but the server has mongo 3.4.4 and the dev has mongo 3.2.10.
If I add another field to be updated (second arugment), that field gets updated fine, but createdAt remains unchanged.
Automatic createdAt
and updatedAt
fields are populated by mongoose using the timestamps
option as
const schema = new Schema({
// Your schema...
}, {
timestamps: { createdAt: true, updatedAt: false }
})
If you take a look at the source code you'll see that createdAt
is excluded from updates. It's fairly easy though to modify your schema accordingly.
const schema = mongoose.Schema({
name: String,
createdAt: { type: Date, default: Date.now }
});
const Test = mongoose.model('test', schema);
const john = await Test.create({name: 'John Doe'});
console.log(john);
const updatedJohn = await Test.findOneAndUpdate({name: 'John Doe'}, { createdAt: Date.now() });
console.log(updatedJohn);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With