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

181
Vistas
Best way to change mongoose objects without side-effects

Probably the question is a little bit silly, but I came across a simple doubt that is actually taking my mind hostage. :)

I need to recover several objects from the database (in mongo), and then, while sending them to an API server, changing a single property to them, to be sure to put the records in the right status so as soon as I get back a response (that is sent to me on another endpoint, asynchronously). Right now I'm doing this like this:

const SomeModel = mongoose.model('SomeModel');
const items = await SomeModel.find({ someField: 'someValue' });
const promises = items.map(async (item) => {
  await sendItem(item);
  item.status = 'SENT';
  await item.save();
});

await Promise.all(promises);

But as you can see, I'm doing some not-good side-effect on that function: I'm actually manipulating an object that is coming in the function parameters... but how can I achieve the same goal without that, and also without having to do a separate query for each item?

thank you for you kind response, Giacomo.

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

0

const SomeModel = mongoose.model('SomeModel');
const items = await SomeModel.find({ someField: 'someValue' });

const bulkWriteBody = items.map((item)=>{
return {
            updateOne: {
              filter: { _id: item._id },
              update: { $set: {
                  status: 'SENT,
                } }
            },
        };

})

await SomeModel.bulkWrite(bulkWriteBody);

with this you do only one promise to update all sent item and you don't need to manual update it.

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