简体   繁体   中英

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!

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);

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

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.

If you plan to validate the data that is received you could create the update object with all fields that are valid. For example:

// Example post
const req = {
    body: {
        name: "First Last",
        email: "app@app.com",
        somethingElse: "I snuck in another update!"
    }
}

// Create update obj
const update = {}

// Destrcture the body to make if statments smaller to read
const {name,email,password} = req.body

// Test all values and add valide ones to update
if(name !== undefined && typeof name === 'string') {
    update.name = name
}

if(email !== undefined && typeof name === 'string') {
    update.email = email
}

if(password !== undefined && typeof password === 'string') {
    update.password = password
}

console.log(update)

Now use that update object inside your Mongo update. Of course you'd want to adjust the validations to check for things like email formatting or password requirements, plus probably cleaner to put them in a function but you get the idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM