简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM