[英]Mongodb: how to update a field only if the value I want to upload is not null?
我有一個名為“profilePicture”的字段,它可以有一個字符串或一個空值。 在編輯他的個人資料時,用戶可能會也可能不會上傳新的個人資料圖片。 這意味着我可以接收字符串或空值。
僅當新值不為空時,如何更新 profilePicture(以便我可以保留現有字符串)?
這是代碼:
const newProfilePicture = null // can be null or "string" const user = await User.findByIdAndUpdate( userId, [{$set: { profilePicture: newProfilePicture }}] { new: true } );
謝謝!
嘗試這個
const updateObj = {};
// other properties added to object
// e.g.
// updateObj.name = "DoneDeal0";
if (newProfilePicture !== null) {
updateObj.profilePicture = "https://profilepicture.etc/picture.jpg";
}
const user = await User.findByIdAndUpdate(
{ userId:"someID" },
{ $set: updateObj },
{ new: true }
);
在 mongo 查詢之前使用條件邏輯構建對象。
我會使用應用程序邏輯來做到這一點。 您可以預先檢查newProfilePicture
是否為空,如果不執行更新。 像這樣的東西:
const newProfilePicture = null;
if (newProfilePicture){
const user = await User.findByIdAndUpdate(
userId,
[{$set: { profilePicture: newProfilePicture }}]
{ new: true }
);
}
如果無論是否實際發生更新都需要返回user
,您只需添加一個else
分支並執行正常的findById
:
const newProfilePicture = null;
if (newProfilePicture){
const user = await User.findByIdAndUpdate(
userId,
[{$set: { profilePicture: newProfilePicture }}]
{ new: true }
);
} else {
const user = await User.findById(userId);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.