简体   繁体   中英

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? I'm running meteor 1.3.

The problem is that you are passing the same object to insert() across iterations.

The mongo driver does not clone the inserted document. instead, it generates an _id for it if one does not exist and adds it to its operations list.

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 . which results in only 1 actual document insertion.

To fix this, pass a fresh object in each iteration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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