16
votes

I have a collection with the _id field as a IP with type String.

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 }

2
What version are you using?WiredPrairie
It also is odd that it's returning "dup key: { : null }` rather than the value of the key that you had tried to insert.WiredPrairie
Is that the full error message? Do you have an index in the servers collection that requires a unique value for each document ...? If you insert two "nulls", you'll get that with the second "null" value.WiredPrairie

2 Answers

35
votes

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:

> 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"
    }
]
7
votes

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).