Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

262
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda