[英]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.