سؤال

I'm trying to insert several documents trough a loop, but I get a problem with the uniqueness of the ObjecId's.

I have this 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');
    });
  }
}); 

I get a "mongoError: E110000 Duplicate key error index: ... " after the first document is created and inserted.

Question: Why are this loop trying to insert every document with the same ObjectID, and therefore generation an error? How do i rewrite this to make sure the ObjectId is random every time?

هل كانت مفيدة؟

المحلول

On the first insert, doc is modified to have the new _id field. Which means that you need to reset it at the start of your for loop as drivers don't add a new _id value to a document if there is already one.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top