Home > database >  Best way to change mongoose objects without side-effects
Best way to change mongoose objects without side-effects

Time:01-28

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.

CodePudding user response:

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.

  •  Tags:  
  • Related