mongoose icon indicating copy to clipboard operation
mongoose copied to clipboard

#feature findOneAndReplace

Open M4rkFlor opened this issue 8 years ago • 4 comments

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

M4rkFlor avatar Apr 15 '18 21:04 M4rkFlor

Model has a method called replaceOne. I think this is what you’re looking for.

ghost avatar Apr 15 '18 22:04 ghost

Wow I did not realize, thank you for pointing that out.

M4rkFlor avatar Apr 16 '18 04:04 M4rkFlor

@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 avatar Oct 21 '18 21:10 fmeynard

@fmeynard That's a good point, opened a new issue ☝️

ghost avatar Oct 24 '18 10:10 ghost