#feature findOneAndReplace
feature
What is the current behavior? Currently To replace a document you need to Model.findOneAndRemove() then NewDoc.save() in my case i'm saving it first to check if it already exists then if it dose i delete it and then save again to replace the deleted picture document.
TempPicObj.save(function (err, origCBPicObj) {
if (err) {
//pic with same name
/////////////////////////////vvvvv//This is what can be Optimized//vvvvvv/////////////
Picture.findOneAndRemove({
'picAdress': TempPicObj.picAdress
}, function (err, result) {
if (err) {
console.error(err);
return (null);
}
console.log("deleted Object:" + result.picAdress);
//save again now that the document the document with same name has been deleted
TempPicObj.save(function (err, CallbackObj) {
if (err) {
console.error(err);
return (null);
}
console.log("sucessfully replaced: " + CallbackObj.picAdress);
return (CallbackObj);
});
return (result);
});
console.error(err);
return (null);
////////////^^^^^^^^//This is what can be Optimized///^^^^^^^/////////////
}
console.log("sucessfully saved " + origCBPicObj.picAdress);
return (origCBPicObj);
});
This can be reduced to one Step with Model.findOneAndReplace()
Picture.findOneAndReplace({
'picName ': TempPicObj.picName
}, TempPicObj, function (err, result) {
if (err) {
console.error(err);
return (null);
}
console.log("replaced Object:" + result.picName );
return (result);
});
MongoDB v3.6.3 Mongoose v5.0.14 Node v8.11.1
Model has a method called replaceOne. I think this is what you’re looking for.
Wow I did not realize, thank you for pointing that out.
@lineus
Can you consider reopening this one ?
A findOneAndReplace function calling the native mongoose function with similar name would allow us to only have 1 mongo query to retrieve the updated document instead of 2 using the replaceOne() function.
@fmeynard That's a good point, opened a new issue ☝️