![](/img/trans.png)
[英]When using findOneAndUpdate(), how to leave fields as is if no value provided (instead of overwriting with null)?
[英]Mongoose findOneAndUpdate only update fields if there is no value or it's null otherwise leave as it is
仅当字段没有值时如何更新?
//...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
这只是一个例子。 我只想知道我们是否可以仅在没有值的情况下更新名称字段值,否则保持字段值不变。
你可以用这个
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.