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

301
Visualizações
Mongoose delete other objects after update

I'm having trouble with my update query on mongoose. I'm not sure why other objects get deleted after I update a specific object. the code works when I update but after that, the rest of the objects inside the array are getting deleted/removed. Literally, all of the remaining objects get deleted after the update request.

export const updateProduct = async (req,res) => {
     const { id } = req.params;
 
     try {
         if(!mongoose.Types.ObjectId.isValid(id)) return res.status(404).json({ message: 'Invalid ID' });
 
         await OwnerModels.findOneAndUpdate({'_id': id, store:{$elemMatch: {productname: req.body.store[0].productname }}},
             {$set: 
                 {
                     store: 
                         {
                             productname: req.body.store[0].productname,
                             price: req.body.store[0].price,
                             quantity: req.body.store[0].quantity,
                             categoryfilter: req.body.store[0].categoryfilter,
                             description: req.body.store[0].description,
                             timestamp: req.body.store[0].timestamp                        
                         }
                 }
         }, // list fields you like to change
         {'new': true, 'safe': true, 'upsert': true});
 
     } catch (error) {
         res.status(404).json(error)
     } }
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I'm not sure why other objects get deleted after I update a specific object.

Because you are updating the whole object and it will replace the existing store array of object in the database,

You need to use arraFilters, and upsert is not effective in array of object updated, so i have commented,

await OwnerModels.findOneAndUpdate(
    {
        '_id': id, 
        store:{
            $elemMatch: {
                productname: req.body.store[0].productname 
            }
        }
    },
    {
        $set: {
            store: {
                "store.$[s].productname": req.body.store[0].productname,
                "store.$[s].price": req.body.store[0].price,
                "store.$[s].quantity": req.body.store[0].quantity,
                "store.$[s].categoryfilter": req.body.store[0].categoryfilter,
                "store.$[s].description": req.body.store[0].description,
                "store.$[s].timestamp": req.body.store[0].timestamp
            }
        }
    },
    {
        'arrayFilters': [
            { "s.productname": req.body.store[0].productname }
        ],
        'new': true, 
        'safe': true, 
        // 'upsert': true
    }
);
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