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

182
Visualizações
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 Respostas
Responde à pergunta

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