Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

261
Views
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.

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!