简体   繁体   中英

Mongoose findOneAndUpdate only update fields if there is no value or it's null otherwise leave as it is

How can I update only if there is no value on fields?

//...just a sample code snippet

const {name, email, phone} = data;
const user = await User.findOneAndUpdate(
   { email},
   { name // only update if not exists or null or no value },
   {new:true,upsert: true}
)

console.log(user}

//...code 

This is just an example. I just want to know if we can update the name field value only if there is no value else leave the field value as it is.

You can use this

const {name, email, phone} = data;
let user = await User.findOne({ email}, { name });

if(!user) {
  user = new User({name, email, phone});
} else {
  if(!user['name')) {
    user['name'] = name;
  }
}
await user.save();

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