I’m using the Node.js native 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 tweak 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 do I get the error message?
The driver adds an
_idkey to yourjsonobject on the first insert, so on the second insert yourjsonhas a_idwitch is duplicate.https://github.com/mongodb/node-mongodb-native/blob/master/lib/mongodb/collection.js