为什么MongoDB无法连续两次插入相同的JSON?

我正在使用Node.js本地驱动程序。 以下工作正常

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(); }); }); 

我在数据库中得到以下内容

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

但是当我调整如下

 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(); }); }); 

我得到以下错误

MongoError:E11000重复键错误索引:

为什么我会收到错误信息?

驱动程序在第一次插入时向您的json对象添加_id键,所以在第二次插入时,您的json有一个_id女巫是重复的。

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(); } 

我同意CD,除了解决scheme比这更容易:

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