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

243
Vistas
Is there a way to update an object in an array of a document by query in Mongoose?

I have got a data structure:


{
  field: 1, 
  field: 3,
  field: [
    { _id: xxx , subfield: 1 },
    { _id: xxx , subfield: 1 },
  ] 
}

I need to update a certain element in the array.

So far I can only do that by pulling out old object and pushing in a new one, but it changes the file order.

My implementation:

            const product = await ProductModel.findOne({ _id: productID });
            const price = product.prices.find( (price: any) => price._id == id );

            if(!price) {
                throw {
                    type: 'ProductPriceError',
                    code: 404,
                    message: `Coundn't find price with provided ID: ${id}`,
                    success: false,
                }
            }

            product.prices.pull({ _id: id })
            product.prices.push(Object.assign(price, payload))
            await product.save()

and I wonder if there is any atomic way to implement that. Because this approach doesn't seem to be secured.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Yes, you can update a particular object in the array if you can find it. Have a look at the positional '$' operator here.

Your current implementation using mongoose will then be somewhat like this:

 await ProductModel.updateOne(
      { _id: productID, 'prices._id': id },//Finding Product with the particular price
      { $set: { 'prices.$.subField': subFieldValue } },
 );

Notice the '$' symbol in prices.$.subField. MongoDB is smart enough to only update the element at the index which was found by the query.

about 4 years ago · Juan Pablo Isaza 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