用Mongoskin插入多个文档到MongoDB中

我试图通过一个循环插入几个文档,但是我遇到了ObjecId的唯一性问题。

我有这个function:

// Fetch all client documents. db.collection('clients').find({}, {cost: 1}).toArray(function(err, dbDocs) { if (err) throw err; // Set up a general doc. var currentTime = new Date(); var doc = { year: currentTime.getFullYear(), quarter: Math.floor(currentTime.getMonth() / 3) + 1, paid: false }; // For each client document, insert a document to invoices collection. for (var i = 0, j = dbDocs.length; i < j; i += 1) { doc.quarterCost = (dbDocs[i].cost.monthly * 3); doc.client_id = dbDocs[i]._id; db.collection('invoices').insert(doc, function(err, result) { if (err) throw err; if (result) console.log('Invoice created'); }); } }); 

创build并插入第一个文档后,出现“mongoError:E110000 Duplicate key error index:…”。

问题: 为什么这个循环尝试插入每个具有相同ObjectID的文档,并因此产生一个错误? 我如何重写这个以确保ObjectId是随机的?

在第一次插入时, doc被修改为具有新的_id字段。 这意味着您需要在for循环开始时将其重置,因为如果已经有一个驱动程序没有为文档添加新的_id值。