我使用的是 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/