【问题标题】:mongo _id field duplicate key errormongo _id 字段重复键错误
【发布时间】:2013-06-11 11:29:08
【问题描述】:

我有一个 _id 字段作为 IP 类型的集合。

我正在使用猫鼬,但控制台上的错误如下:

$ db.servers.remove()

$ db.servers.insert({"_id":"1.2.3.4"})

$ db.servers.insert({"_id":"1.2.3.5"})

【问题讨论】:

  • 你用的是什么版本?
  • 它返回“dup key: { : null }` 而不是您尝试插入的键的值也很奇怪。
  • 这是完整的错误信息吗?您在服务器集合中是否有一个索引,该索引需要每个文档的唯一值...?如果你插入两个“null”,你会得到第二个“null”值。

标签: mongodb mongoose


【解决方案1】:

很可能是因为您有一个索引,该索引要求其中一个字段具有唯一值,如下所示:

> 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 }

您可以在集合上使用 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"
    }
]

【讨论】:

  • 就是这样,谢谢。我一定是在我的 mongoose 模式中删除了该字段,但忽略了删除集合。
  • 一开始我对这个错误感到困惑,直到我意识到它在抱怨null。 :)
  • @WiredPRairie 很棒! :)
  • 我只是做了同样的事情!谢谢
【解决方案2】:

我今天被完全相同的错误弄糊涂了,后来想通了。这是因为我从 mongoose 模式中删除了一个索引属性,但没有从 mongodb 索引中删除该属性。错误消息实际上是新文档具有值为 null 的索引属性(不在 json 中)。

【讨论】:

  • 含义:登录Mongo数据库,进入相应的集合,从那里删除索引
猜你喜欢
  • 2015-04-30
  • 1970-01-01
  • 2015-05-11
  • 2015-03-16
  • 1970-01-01
  • 2014-10-02
  • 2021-07-25
  • 2018-12-30
  • 1970-01-01
相关资源
最近更新 更多