You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Mongoose的updateMany中间件提升批量数据更新性能?

已解决:解决方案在文末

我现有如下逐元素执行更新的代码:

//registerCustomers.js
const CustomerRegistrationCode = require("../models/CustomerRegistrationCode");

const setRegCodesToUsed = async (regCodes) => {
  for (let regCode of regCodes) {
    await setRegCodeToUsed(regCode._id);
  }
};

const setRegCodeToUsed = async (id) => {
  await CustomerRegistrationCode.findByIdAndUpdate(id, { used: true });
};

这段代码可以正常运行但速度过慢,我希望一次性批量更新1000条CustomerRegistrationCode记录。我查阅了updateMany中间件相关功能,但网络上和官方文档相关说明较少,我将代码修改为如下形式后不知道该如何继续开发:

//registerCustomers.js
const setRegCodesToUsed = async (regCodes) => {
  await CustomerRegistrationCode.updateMany(regCodes);
}
//CustomerRegistrationCode.js
CustomerRegistrationCodeSchema.pre('updateMany', async function (next, a) {
  console.log('amount arguments: ', arguments.length); //is 2
  console.log(arguments); //both parameters are functions.
  next();
});

请问针对包含1000个不同id的CustomerRegistrationCode记录,最优的批量更新实现方式是什么?


解决方案(感谢Murat Colyaran提供)

const setRegCodesToUsed = async (regCodes) => {
  const ids = [];
  regCodes.map(code => ids.push(code._id));
  await setRegCodeToUsed(ids);
};

const setRegCodeToUsed = async (ids) => {
  await CustomerRegistrationCode.updateMany(
    { _id: { $in: ids } },
    { used: true }
  );
};

内容的提问来源于stack exchange,提问作者swftowu69

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 19:27:03