【问题标题】:How do I use insertMany with Mongoose when I have a big array of object?当我有大量对象时,如何将 insertMany 与 Mongoose 一起使用?
【发布时间】:2018-03-07 13:03:33
【问题描述】:

我正在尝试使用 insertMany 方法,但没有成功...我阅读了这个 stackoverflow answer,但它没有说明如何处理非常大的对象数组。

在我的测试用例中,我有 9755 个对象,使用此脚本将所有行导入 9 次,这不是我想要的...

我想在每次导入时将数组分成 1000 个对象的块。

我该怎么做?

function bulkImportToMongo(arrayToImport, mongooseModel) {
  const Model = require(`../../../models/${mongooseModel}`);
  let counter = 0;
  let temp = [];
  arrayToImport.forEach(item => {
    temp.push(item);
    counter++;

    if (counter % 1000 == 0) {
      Model.insertMany(temp).then(mongoosedocs => {
        console.log(`imported ${counter} objects`);
        console.log(mongoosedocs.length);
        temp = [];
      });
    }
  });
}

【问题讨论】:

    标签: mongoose promise


    【解决方案1】:

    您需要创建一个批次数组(每个批次不超过 100 个元素)。对于每个批处理调用Model.insertMany。要等到所有文档都插入,你Promise.all

    function bulkImportToMongo(arrayToImport, mongooseModel) {
      const Model = require(`../../../models/${mongooseModel}`);
      const batchSize = 100;
      let batchCount = Math.ceil(arrayToImport.length / batchSize);
      let recordsLeft = arrayToImport.length;
      let ops = [];
      let counter = 0;
      for (let i = 0; i < batchCount; i++) {
        let batch = arrayToImport.slice(counter, counter + batchSize);
        counter += batchSize;
        ops.push(Model.insertMany(batch));
      }
      return Promise.all(ops);
    }
    

    【讨论】:

    • 未处理的拒绝语法错误:标识符“批次”已被声明。我应该删除“let batch =”吗?
    • 不,我已经修复了示例。
    • 谢谢!仍然不适合我。 :-(。如果你有时间看看,这里是完整的代码。repl.it/LdUd/5
    • 很遗憾我无法修复您代码中的所有错误,您提出了有关具体问题的问题,我已经提供了答案。
    • 在您的代码示例中发现一个问题,在Math.ceil 中修复batchSize,而不是1000,使用100。
    猜你喜欢
    • 2021-01-02
    • 2012-08-19
    • 2020-01-17
    • 2012-09-16
    • 1970-01-01
    • 2020-07-12
    • 1970-01-01
    • 1970-01-01
    • 2019-12-03
    相关资源
    最近更新 更多