2
我想通过一个循环插入几个文档,但是我遇到了ObjecId的唯一性问题。用Mongoskin将多个文档插入到MongoDB中
我有这样的功能:
// 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');
});
}
});
我得到一个“mongoError:E110000重复键错误指数:......”第一个文件被创建并插入之后。
问:为什么此环路尝试每一个文档中插入使用相同的对象ID,因此产生一个错误? 如何重写这个以确保ObjectId每次都是随机的?