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

181
Visualizações
Mongoose update array value

How to update array value in mongoose ?

This is my schema

var cars = new Schema({
    brand : String,
    prices:[ {color : String, price: String}]
}





   let carID = req.body.carID;
   let brandPriceArraySingleID = req.body.brandPriceArraySingleID;
    
    var ObjectId = require('mongoose').Types.ObjectId; 
    var query = { 'prices.id' : new ObjectId(brandPriceArraySingleID) };
    
    let carsPriceUpdate = await cars.findOneAndUpdate(query, { $set: { "price": "new price" } });

This above code is not working!!

Questions

  1. How to find and update array value?
  2. Do I need to check whether exist carID in cars model before array value find?
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

If you want to update the Array fields element from the query, you need to use $ in the field, ex : { "prices.$.price": "new price" }

Try this code.

   const query = {
     _id : req.body.carID,
     "prices._id" : req.body.brandPriceArraySingleID
    }

  let carsPriceUpdate = await cars.findOneAndUpdate(query, { $set: { "prices.$.price": "new price" },{ returnDocument: 'after' }});

   console.log(carsPriceUpdate)
  1. You need to set new value for the object's property ( $ reflects the position).
  2. { returnDocument: 'after' } is options of query. it's return document after updating.
over 4 years ago · Santiago Trujillo 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