繁体   English   中英

流星散装插入仅插入最后一个项目

[英]meteor bulk insert only inserts last item

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

'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。

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

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

_id仅在您的情况下在第一次迭代中生成,因此基本上指示MongoDB使用save _id插入100个文档。 实际只能插入1个文档。

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

暂无
暂无

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

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