I am in a situation where i want to update documents of collection in mongodb but i don't want "updatedAt" field to be updated. I want to retain the previous value of updated field. Please help.
Asked
Active
Viewed 4,157 times
5
-
if no need to update `updatedAt` filed on update then why need `updatedAt` field ? – Shaishab Roy Jan 20 '17 at 09:44
-
3I want to retain the previous value of updated field. – Vikash_Singh Jan 20 '17 at 09:47
-
1Mongo does not update the value of any user defined field on its own. If you don't want to update a field simply don't update it. – Jyotman Singh Jan 20 '17 at 09:47
-
2I replied in this question [Skip timestamps middleware for certain updates in Mongoose](https://stackoverflow.com/questions/38621790/skip-timestamps-middleware-for-certain-updates-in-mongoose/45707811#45707811). Hope this help! – Trung Le Nguyen Nhat Aug 16 '17 at 07:45
-
1thanks $set solves this problem. – Vikash_Singh Jul 28 '18 at 06:29
3 Answers
1
If you are using Waterline or other database abstractions, my advice is to run the query natively in mongo.
This is how I would fix this in Sails.js (running Waterline):
let someQuery = {name: 'John Doe'};
MyModel.native(function (err, collection){
collection.update(
{query: someQuery}, // Which documents to update?
{$set:{field1: "value", foo:"bar"}}, // Our new values
{multi: true}, // To support update of multiple fields
function(err, result){
if (err) console.log(err)
else console.log(result.result)
})
});

qualbeen
- 1,534
- 4
- 16
- 27
1
updatedAt field is updated when you use update query of mongoose. if we directly use $set query it will only update the mentioned fields inside $ set query. The reason is updatedAt field is managed by mongoose not by mongodb.

anj
- 162
- 2
- 7

Vikash_Singh
- 1,856
- 2
- 14
- 27
-
The $set alone is not sufficient on mongodb version 4.2.3. { timestamps: false } should be used with the $set. https://stackoverflow.com/a/64634344/6003002 – blokberg Sep 13 '22 at 15:50
1
If you are using mongoose, then relatively new feature (2020) gives you the option to override setting timestamps (or just one) on transactions.
Example from docs shown below
const userSchema = mongoose.Schema({
email: String
}, { timestamps: true });
const User = mongoose.model('User', userSchema);
const doc = await User.findOneAndUpdate({email: 'test@google.com'}, {email:'newtest@google.com'},
{new:true, upsert: true, timestamps:false});

Phil Moir
- 121
- 1
- 6