![](/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.