mongodb mongo _id 字段重复键错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17114851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
mongo _id field duplicate key error
提问by EthernetCable
I have a collection with the _id field as a IP with type String.
我有一个 _id 字段作为字符串类型的 IP 的集合。
I'm using mongoose, but here's the error on the console:
我正在使用猫鼬,但这是控制台上的错误:
$ db.servers.remove()
$ db.servers.insert({"_id":"1.2.3.4"})
$ db.servers.insert({"_id":"1.2.3.5"}) <-- Throws dup key: { : null }
$ db.servers.remove()
$ db.servers.insert({"_id":"1.2.3.4"})
$ db.servers.insert({"_id":"1.2.3.5"}) <-- 抛出重复键:{ : null }
回答by WiredPrairie
Likely, it's because you have an index that requires a unique value for one of the fields as shown below:
很可能,这是因为您有一个索引,需要其中一个字段的唯一值,如下所示:
> db.servers.remove()
> db.servers.ensureIndex({"name": 1}, { unique: 1})
> db.servers.insert({"_id": "1.2.3"})
> db.servers.insert({"_id": "1.2.4"})
E11000 duplicate key error index: test.servers.$name_1 dup key: { : null }
You can see your indexes using getIndexes()
on the collection:
您可以getIndexes()
在集合上查看索引:
> db.servers.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"ns" : "test.servers",
"name" : "_id_"
},
{
"v" : 1,
"key" : {
"name" : 1
},
"unique" : true,
"ns" : "test.servers",
"name" : "name_1"
}
]
回答by dliu
I was confused by exactly the same error today, and later figured it out. It was because I removed a indexed property from a mongoose schema, but did not drop that property from the mongodb index. The error message is infact that the new document has an indexed property whose value is null (not in the json).
我今天被完全相同的错误弄糊涂了,后来想通了。这是因为我从 mongoose 模式中删除了一个索引属性,但没有从 mongodb 索引中删除该属性。错误消息实际上是新文档有一个索引属性,其值为空(不在 json 中)。