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

我收到以下错误

Mongo错误: 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,除了解决方案比这更容易:

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

最新更新