简体   繁体   English

无副作用更改 mongoose 对象的最佳方法

[英]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).我需要从数据库中恢复几个对象(在 mongo 中),然后在将它们发送到 API 服务器时,将单个属性更改为它们,以确保将记录置于正确的状态,以便我一回来一个响应(在另一个端点上异步发送给我)。 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?但正如你所看到的,我对 function 做了一些不好的副作用:我实际上是在操纵 ZC1C425268E68385D1AB5074C17A94F1 中的 object也不必对每个项目进行单独的查询?

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.有了这个,你只需要一个 promise 来更新所有发送的项目,你不需要手动更新它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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