简体   繁体   中英

How to check if key exists on mongoose document?

I have a User Model and recently added some key to it. 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.

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. I also tried if("applications" in user) . That also does not work.

So how can I check if a key or field exists on a Mongoose object.

A simple way of checking if the field exists or not can be done by $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. So, we can use the $exists operator to check it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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