简体   繁体   English

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

[英]meteor bulk insert only inserts last item

I am trying to do a bulk insert as in this method: 我正在尝试按此方法进行批量插入:

'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.");
    }
  }

How come only item with number 99 gets inserted when trying to add 100 test questions? 尝试添加100个测试问题时,为什么只插入编号为99的项目? I'm running meteor 1.3. 我正在运行流星1.3。

The problem is that you are passing the same object to insert() across iterations. 问题是您要在迭代中将同一对象传递给insert()

The mongo driver does not clone the inserted document. mongo驱动程序不会克隆插入的文档。 instead, it generates an _id for it if one does not exist and adds it to its operations list. 相反,如果它不存在,它将为其生成一个_id并将其添加到其操作列表中。

The _id is only generated in the first iteration in your case, so MongoDB is basically instructed to insert 100 documents with the save _id . _id仅在您的情况下在第一次迭代中生成,因此基本上指示MongoDB使用save _id插入100个文档。 which results in only 1 actual document insertion. 实际只能插入1个文档。

To fix this, pass a fresh object in each iteration. 要解决此问题,请在每次迭代中传递一个新对象。

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

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