meteor bulk insert仅插入最后一项

时间:2016-04-08 23:52:21

标签: javascript node.js meteor

我正在尝试按此方法执行批量插入:

'createTestQuestionBatch'(limit) {
    check(limit, Number);

    if (Meteor.isServer) {
      const questionItem = {
        question: "Question will be reconstructed with a number",
        category: "n3f98f4b22v948nb4v2fg4b89",
        answer: ["Yes", "No", "Maybe", "Probably"],
        localization: "en",
        testQuestion: true,
      };

      var bulk = Question.rawCollection().initializeUnorderedBulkOp();

      for (var i = 0; i < limit; i++) {
        questionItem.question = "Is this test question number " + i + "?";
        bulk.insert(questionItem);
      }

      bulk.execute(function (err) {
        if (err) {
          throw new Meteor.Error('createTestQuestionBatch', 'Bulk update operation failed.' + err);
        } else {
          console.log("Bulk question creation operation completed. " + limit + " items has been inserted.");
        }
      });
    } else {
      console.log("Bulk operation for creating tests are running on the server. Server logs will notify when operation has completed.");
    }
  }

在尝试添加100个测试题时,如何才会插入编号为99的项目?我正在运行流星1.3。

1 个答案:

答案 0 :(得分:1)

问题是您在迭代过程中将同一个对象传递给insert()

mongo驱动程序不克隆插入的文档。相反,如果不存在,则为它生成_id,并将其添加到其操作列表中。

_id仅在您的案例的第一次迭代中生成,因此基本上指示MongoDB使用save _id插入100个文档。这导致只有1个实际文件插入。

要解决此问题,请在每次迭代中传递一个新对象。