FORTRAN
FORTRAN

Reputation: 637

Mongo fails to create unique _id when inserting

I'm building a node.js app and tries to insert several documents to a collection at once but It fails with an error

E11000 duplicate key error index: mydb.mycollection.$_id_  dup key: { : ObjectId('52f0ce126bee2f405a755c6b') }

Here is code that gives me that error

var my_docs = new Array;
var tmp = {'name':'','address':''};
for (var i=0; i < limit ; i++)
{
   my_docs.push(tmp);
}
db.collection('mycollection').insert(my_docs,{w:1}, function(err, result) {...

This is very strange. Any ideas on how to proceed to debug this?

If I do manual insert from commandline, it works and no key duplications.

Upvotes: 0

Views: 83

Answers (1)

chekkal
chekkal

Reputation: 307

I think this problem is due to the fact that your tmp var refer to the same object along your for loop, try the following:

var my_docs = new Array;

for (var i=0; i < limit ; i++)
{
  var tmp = new Object({'name':'','address':''});
  my_docs.push(tmp);
}
db.collection('mycollection').insert(my_docs,{w:1}, function(err, result) {...

Upvotes: 3

Related Questions