简体   繁体   English

如何检查 mongoose 文档中是否存在密钥?

[英]How to check if key exists on mongoose document?

I have a User Model and recently added some key to it.我有一个User Model ,最近向它添加了一些密钥。 This means that existing users will not have this key initially and new users do.这意味着现有用户最初不会拥有此密钥,而新用户拥有。 Now I have a route where I want to check if the particular key exists on the user object so that I can add it if it returns false.现在我有一条路线,我想检查用户 object 上是否存在特定密钥,以便在它返回 false 时添加它。

This is my route currently:这是我目前的路线:

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();
    });
});

The problem is that if (user.hasOwnProperty("applications")) always returns false even after I added it to the user.问题是if (user.hasOwnProperty("applications"))即使在我将它添加到用户之后也总是返回 false。 I also tried if("applications" in user) .我也试过if("applications" in user) That also does not work.那也行不通。

So how can I check if a key or field exists on a Mongoose object.那么如何检查 Mongoose object 上是否存在键或字段。

A simple way of checking if the field exists or not can be done by $exist .检查字段是否存在的简单方法可以通过$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();
    });
});

Note: the reason your old user doesn't show the applications is they don't have it when you saved them and changing the model now won't add this property to old models.注意:您的旧用户不显示applications的原因是当您保存它们时他们没有它并且现在更改 model 不会将此属性添加到旧模型。 So, we can use the $exists operator to check it.因此,我们可以使用$exists运算符来检查它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM