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

106
Vistas
mongoose how to update properties in document only if they exist in request?

In order to update a document i usually do as such...

  Model.findById(id)
.then((doc) => {
  doc.fName = req.body.fName
    ? req.body.fName
    : doc.fName;
  doc.lName = req.body.lName 
  ? req.body.lName
  : doc.lName
  return doc.save();
})
.then((result) => res.send(" Succesfully updated ! New data: " + result))
.catch((err) => res.send(err));

..which checks if the field actually exists in the body request,otherwise it just passes the previous value.

Is there a way to just provide the fields in the request and let it do the check for itself so if a field does not exist,it will not delete it ? like so...

  Model.someMethod(id)
.then((doc) => {
  doc.fName = req.body.fName
  doc.lName = req.body.lName
  return doc.save();
})
.then((result) => res.send(" Succesfully updated ! New data: " + result))
.catch((err) => res.send(err));
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Using it in this way will only update the same field that you enter in the req.body.Other fields will be as it is. Which is in the fields NOT_ALLOWED variable will not be updated.

const NOT_ALLOWED = ['_id'] //Just the same field will update which are not in this variable
     Model.findById(id).then((docs) => {
        Object.keys(req.body).map((key) => {

            if (NOT_ALLOWED.indexOf(key) === -1) {
                docs[key] = req.body[key]
            }

        })
        return docs.save()
    })
        .then((result) => console.log("Updated Data", result))
        .catch((err) => res.send(err));
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can do that with one update query. First, you can construct the update config based on all the properties from the req.body. Then, just pass that update config to the update query. You can also pass { new: true } as third config to update query, so the updated document will be returned.

let update = {};
if (req.body.fName) update.fName = req.body.fName;
if (req.body.lName) update.lName = req.body.lName;

Model.findByIdAndUpdate(id, update, { new: true })
  .then((result) => res.send(" Succesfully updated ! New data: " + result))
  .catch((err) => res.send(err));
about 4 years ago · Juan Pablo Isaza 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