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

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

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 Relatório

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 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