Why can't MongoDB insert the same JSON twice in a row?

I use the native Node.js. driver The following works fine

db.collection("test").insert({hello:'world_safe'}, {safe: true}, function(err, result) { if (err) throw err; db.collection("test").insert({hello:'world_safe'}, {safe: true}, function(err, result) { if (err) throw err; db.close(); }); }); 

I get the following in the database

{"hello": "world_safe", "_id": ObjectId ("4fe978c8b8a5937d62000001")} {"hello": "world_safe", "_id": ObjectId ("4fe978c8b8a5937d62000002")}

However, when I configure as follows

 var json = {hello:'world_safe'}; db.collection("test").insert(json, {safe: true}, function(err, result) { if (err) throw err; db.collection("test").insert(json, {safe: true}, function(err, result) { if (err) throw err; db.close(); }); }); 

I get the following error

MongoError: E11000 duplicate key error index:

Why am I getting an error message?

+4
source share
2 answers

The driver adds the _id key to your json object in the first insert, so the second insert of your json has the _id character, which is duplicated.

https://github.com/mongodb/node-mongodb-native/blob/master/lib/mongodb/collection.js

 // Add id to each document if it not already defined if (!(Buffer.isBuffer(doc)) && doc['_id'] == null && self.db.forceServerObjectId != true) { doc['_id'] = self.pkFactory.createPk(); } 
+5
source

I agree with the CD, except that the solution is simpler than this:

 /* ... before insert */ if(typeof(collection._id) != 'undefined') delete collection._id; /* ... now insert */ 
0
source

All Articles