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

标签 node.js mongodb

我使用的是 Node.js native 驱动程序。以下工作正常

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 duplicate key error index:

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

最佳答案

驱动程序在第一次插入时向您的 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();
    }

关于node.js - 为什么 MongoDB 无法连续两次插入相同的 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11203888/

相关文章:

javascript - 读取代码点时出现偏移问题

mongodb - MongoDB 中 V8 JavaScript 引擎对 map reduce 的好处

mongodb - 应该如何声明上下文?

node.js - 如何为两个静态文件夹配置nginx

javascript - 使用 Graphql 时在 Mongoose 模式中填充 "Ref"

javascript - npm 参数导致 "Insufficient number of arguments or no entry found"

node.js - 无法从我的 VS 代码扩展 (node.js) 连接到 SQL Server

node.js - Express:保持所有 DRY 创建 mongoose 连接模块(使用新的 createConnection 方法)

node.js - NodeJs 的数据库访问是阻塞操作吗

mongodb - mongoDB安装错误