Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

254
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda