Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using findOneAndUpdate(), how to leave fields as is if no value provided (instead of overwriting with null)?

The user has the option of updating any of a few values - however, if he only passes in { name: "new name" }, the email and password fields are also updated but to "null".

How can I only update the fields that are actually provided in req.body, leaving the rest as they are?

This is while still specifying which fields can be updated with a POST request - I've avoided just passing in req.body because I'd like to limit this.

My code looks like:

db.User.findOneAndUpdate({_id: req.params.id}, { 
        name: req.body.name,
        email: req.body.emaill, 
        password: req.body.password
})

Using something like name: req.body.name && req.body.name to check if a value is not undefined also overwrites with "null".

Thanks!

like image 634
dan674 Avatar asked Dec 18 '17 22:12

dan674


People also ask

How do you use findOneAndUpdate?

Getting Started. You need at least 2 parameters to call findOneAndUpdate() : filter and update . MongoDB finds the first document that matches filter and applies update . By default, findOneAndUpdate() returns the document as it was before MongoDB applied update .

What is difference between updateOne and findOneAndUpdate?

findOneAndUpdate returns a document whereas updateOne does not (it just returns the _id if it has created a new document). I think that's the main difference. So the use case of updateOne is when you don't need the document and want to save a bit of time and bandwidth.

What does findByIdAndUpdate return?

log() the result. Well, it is because the findByIdAndUpdate() function returns the matching document first and then performs the update operation. It is not reflected in the output but when we look at the database in the MongoDB Compass, you'll see the changes in the document there.

Is findOneAndUpdate atomic MongoDB?

Atomic UpdatesWith the exception of an unindexed upsert, findOneAndUpdate() is atomic. That means you can assume the document doesn't change between when MongoDB finds the document and when it updates the document, unless you're doing an upsert.


1 Answers

Prepare your update object first:

let params = { 
        name: req.body.name,
        email: req.body.emaill, 
        password: req.body.password
};

for(let prop in params) if(!params[prop]) delete params[prop]; //This will not handle intentionally setting to false, empty string, null, 0, or other falsey values.

db.User.findOneAndUpdate({_id: req.params.id}, params);

Or, if your property names match:

let params = {};

for(let prop in req.body) if(req.body[prop]) params[prop] = req.body[prop];

db.User.findOneAndUpdate({_id: req.params.id}, params);
like image 113
N-ate Avatar answered Sep 22 '22 00:09

N-ate