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!
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!
Share Improve this question asked Dec 18, 2017 at 22:27 dan674dan674 2,1273 gold badges17 silver badges22 bronze badges4 Answers
Reset to default 13Prepare 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);
const resu=await this.store.company.findByIdAndUpdate(companyId,
{ $set: { name,dba,description,foundedYear,contactInfo,clients,eVerified,socialMedia} ,
},
{new:true,omitUndefined:true},)
Use omitUndefined:true option
Use the option ignoreUndefined
const { name, email, password } = req.body;
db.User.findOneAndUpdate(
{ _id: req.params.id },
{ $set: {
name,
email,
password
}
},
{ ignoreUndefined: true }
)
How about this?
db.User.findOneAndUpdate({_id: req.params.id}, req.body)
If your request looks exactly like in your sample ({ name: "new name" }
) then this should have the desired effect.