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

528
Vistas
Best way to use Mongoose to update an Array of Objects?

my req.body is this, its coming from my front end so its a couple objects in an array, id like to update based on the records that are matching but the page has changed.

[
[0]   {
[0]     _id: '60393a58c772c12724aa636e',
[0]     title: 'newTitle2',
[0]     page: '8',
[0]     book: '010',
[0]     __v: 0
[0]   },
[0]   {
[0]     _id: '60394e08f6e0ad0bb077e0bc',
[0]     title: 'newTitle3',
[0]     page: '123',
[0]     book: '099',
[0]     __v: 0
[0]   }
[0] ]

My route is this

router.post("/dataSend", async(req, res) => {

let { title, page, book} = req.body;

console.log(req.body)
const filter = { title };
const update = { page};

let doc = await Data.findOneAndUpdate({title:req.body[0].title},{page: req.body[0].page});

res.send(doc)
})

So this will work if I specifiy with mongoose that I want to update the [0] first array, but I would like to update everything, I am not sure if .map or forEach or a loop is the way to go?

Any ideas

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Rather than calling findOneAndUpdate in a loop, I think bulkWrite (docs) would be the better option in this case, so you don't send your updates to Mongo one by one. You can map your update operations and send them in one batch. Please refer to the following snippet for an example:

router.post("/dataSend", async(req, res) => {
  const records = req.body

  const updateOps = records.map(record => {
    const updateOp = {
      'updateOne': {
        'filter': {
          'title': record.title,
        },
        'update': {
          'page': record.page
        },
      }
    }
    
    return updateOp
  })


  const result = await Data.bulkWrite(updateOps)

  res.send(result)
})

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