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

152
Visualizações
how to only update specific fields and leave others with the previous values in findandupdate with Mongoose

I've created an update function using Mongoose. However whenever I update the data using findOneAndUpdate. It updates only the fields entered and making it so that the others are now null or empty. I would like it so that when the user is updating and they dont update a filed it should remain as what it was before instead of being empty now. essentially only update the fields entered.

heres my routes

router.post("/updateStock", (req, res) => {
    const filter = {prodId: req.body.prodID}

    const update = req.body

    Product.findOneAndUpdate(filter, update, {new: true}).then((product) => {
        console.log("success");
        res.send(product);
  }).catch(err => {
       console.log("err", err);
       res.status(500).send(err);
  })

});

here's an example of req.body. I've only updated the title and catergory on the frotnend meaning everything else is blank. When it saves in the DB it ony updates the title and catergory and leaves everything else blank. I would like it to not insert the blank ones into the DB and leave the fields as they are

{
  prodId: 'iPhone 111001200',
  title: 'iPhone 11 Pro',
  manufacturer: '',
  catergory: 'Electronics',
  price: '',
  quantity: ''
}

Here's my model

const mongoose = require("mongoose");

const Product = mongoose.model(
  "Product",
  new mongoose.Schema({
    title: String,
    manufacturer: String,
    price: String,
    catergory: String,
    quantity: String,
    prodID: String, 
    images: Array
  })
);

module.exports = Product;
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Something like this then:

const update = {};
for (const key of Object.keys(req.body)){
    if (req.body[key] !== '') {
        update[key] = req.body[key];
    }
}
test.findOneAndUpdate(filter, {$set: update}, {new: true}).then((product) => {
        console.log("success");
        res.send(product);
  }).catch(err => {
       console.log("err", err);
       res.status(500).send(err);
  })}

You should use the $set only to update the fields that you want to update. In your case, the fields that are not ''.

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