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!
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 .
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With