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 _id
key to your json
object on the first insert, so on the second insert your json
has a _id
witch is duplicate.
https://github.com/mongodb/node-mongodb-native/blob/master/lib/mongodb/collection.js
// Add id to each document if it's not already defined
if (!(Buffer.isBuffer(doc)) && doc['_id'] == null && self.db.forceServerObjectId != true) {
doc['_id'] = self.pkFactory.createPk();
}
I agree with CD, except the solution is easier than that:
/* ... before insert */
if(typeof(collection._id) != 'undefined')
delete collection._id;
/* ... now insert */