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

174
Vistas
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 Respuestas
Responde la pregunta

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