My application uses Mongoose and has a schema that uses the timestamps option:
var fooSchema = new Schema({
name: String,
}, {
timestamps: true,
});
mongoose.model('Foo', fooSchema);
So whenever an update is written to the collection, the updatedAt
property is changed to the current date. But now I would like to add some changes that should not update the updatedAt
property.
Some answers on Stackoverflow (example) suggested to use Foo.collection
as that allegedly accesses the native MongoDB driver. So I tried this:
Foo.collection.update({ _id: someFooId }, { $set: { name: 'New Name' } });
However, that changed the updatedAt
property as well.
So how can I update a document, without changing updatedAt
?
$in -The $in operator selects the documents where the value of a field equals any value in the specified array. 1) {multi:true} to update Multiple documents in mongoose . 2)use update query to update Multiple documents ,If you are using findOneAndUpdate query only one record will be updated.
createdAt: Date representing when the document was created. updatedAt: Date representing when this document was last updated.
Upsert is a combination of insert and update (inSERT + UPdate = upsert). We can use the upsert with different update methods, i.e., update, findAndModify, and replaceOne. Here in MongoDB, the upsert option is a Boolean value. Suppose the value is true and the documents match the specified query filter.
You can also overwrite Mongoose's default _id with your own _id . Just be careful: Mongoose will refuse to save a document that doesn't have an _id , so you're responsible for setting _id if you define your own _id path.
From mongoose 5 onwards , there is timestamps option which can be passed in Model.updateOne() and model.update() to skip timestamps for this update.
Directly from docs:
[options.timestamps=null] «Boolean» If set to false and schema-level timestamps are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set.
For example given in the question , timestamp updates can be skipped like this ,
Foo.updateOne({ __id: someFooId },{ $set: { name: updatedName } }, { timestamps: false });
I just found a solution and it works perfectly to me.
mongoose.connection.db.collection('player').updateOne(
{_id: mongoose.Types.ObjectId('56cb91sf34746f14678934ba')},
{$set: {name: 'Test'}}
);
This query will not update the updatedAt
field. Hope you still need this!
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