Reputation: 10879
Environment
node -v
v10.0.0
// native driver "mongodb": "^3.0.8",
Desired Behavior
I want to update a document and return the original document.
Actual Behavior
The updated document is being returned, instead of the original document.
What I've Tried
Initially I was looking at findAndModify
:
http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#findAndModify
however the docs there say that it is deprecated and to use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead
.
So I tried:
collection.findOneAndUpdate(filter, update, function(err, result) {
if (err) {
res.send(err);
} else {
// find object in array of objects ('statements') and return the 'text' property value
var old_text = result.value.statements.find(x => x.id === "my_great_id").text;
console.log(old_text);
}
});
http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#findOneAndUpdate
The docs say that the option returnOriginal
is default, however it is logging the updated value, rather than the original value.
Edit:
The problem was elsewhere in code - the code above works as expected.
Upvotes: 1
Views: 433
Reputation: 1314
By default findOneAndUpdate
function returns the original document.
But adding {new: false}
to the third parameter of findOneAndUpdate
function may work in your case.
collection.findOneAndUpdate(filter, update, {new: false}, function(err, result) {
if (err) {
res.send(err);
} else {
// find object in array of objects ('statements') and return the 'text' property value
var old_text = result.value.statements.find(x => x.id === "my_great_id").text;
console.log(old_text);
}});
Upvotes: 1