[英]How to check if key exists on mongoose document?
我有一個User Model
,最近向它添加了一些密鑰。 這意味着現有用戶最初不會擁有此密鑰,而新用戶擁有。 現在我有一條路線,我想檢查用戶 object 上是否存在特定密鑰,以便在它返回 false 時添加它。
這是我目前的路線:
router.post("/new-application", verifyUser, (req, res) => {
const { application } = req.body;
User.findById(req.userId)
.then((user) => {
if (user.hasOwnProperty("applications")) {
console.log("has applications");
} else {
console.log("has not applications");
user["applications"] = initialApplications;
}
user.save().then((updatedUser) => {
// console.log(updatedUser);
});
})
.catch((err) => {
console.log("err fetching user: ", err);
res.end();
});
});
問題是if (user.hasOwnProperty("applications"))
即使在我將它添加到用戶之后也總是返回 false。 我也試過if("applications" in user)
。 那也行不通。
那么如何檢查 Mongoose object 上是否存在鍵或字段。
檢查字段是否存在的簡單方法可以通過$exist
來完成。
router.post("/new-application", verifyUser, (req, res) => {
const { application } = req.body;
User.findById({$and: [{_id: req.userId}, {applications: {$exists:false}}]})
.then((user) => {
// it will return the user only when
// applications doesn't exist
})
.catch((err) => {
console.log("err fetching user: ", err);
res.end();
});
});
注意:您的舊用戶不顯示applications
的原因是當您保存它們時他們沒有它並且現在更改 model 不會將此屬性添加到舊模型。 因此,我們可以使用$exists
運算符來檢查它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.