I have an "items" collection and this is an example document in the collection:
{ "id": 0, "price": 23.55 }
I'm updating writing a query that updates an item's price, but want to check if the price field has really modified.
For example, following query is legal but does not actually modify the document.
db.collection('items').updateOne(
{ id: 0 },
{ $set: { price: 23.55 } }
);
Is there any methods I can achieve this?
updateOne will return nModified you can get to know whether the document was modified or not.
{ "n": 1, "nModified": 1 }
https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#updateOne
https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#~updateWriteOpCallback
https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#findOneAndUpdate
Use findOneAndUpdate with returnOriginal set to false, you'll get the updated document in the callback.
const options = { returnOriginal: false; } // to return the updated document
findOneAndUpdate(filter, update, options, callback)
https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#~findAndModifyCallback
Document returned from the findAndModify command. If no documents were found, value will be null by default (returnOriginal: true), even if a document was upserted; if returnOriginal was false, the upserted document will be returned in that case.