7
votes

When trying to enter a new document in mongo with a value on a field that already exist in another document i get this when i iterate through the error object:

for(var att in err){
    console.log(att+": "+err[att]);
}

name: MongoError err: E11000 duplicate key error index: draw.users.$email_1 dup key: { : "[email protected]" } code: 11000 n: 0 ok: 1

So it tells me what i want to know, the problem is the email field. But can I get the offending field as a key/value rather than just a string?

5

5 Answers

4
votes

Using split on the error message returned work for me this way

var x= err.errmsg.split("index:")[1].split("dup key")[0].split("_")[0];
3
votes

I use a regular expression. Like this

if(err){
   field = err.err.match(/\$(.*?)_/)[1]
}

Which is totally hacky but is working for me.

1
votes

In the new version of MongoDB, you can also do that.

Where dupField is a duplicate field name and err.keyValue[dupField] is a duplicate field value.

const handleDuplicateFieldsDB = err => {
    const dupField = Object.keys(err.keyValue)[0];
    return `Duplicate field(${dupField}). Please use another value(${err.keyValue[dupField]})!`;
};
0
votes

If it collides, then making a find() for that query will return you the collision objects and you go from there.

0
votes

The error message doesn't give you the information that you are looking for :

name: MongoError err: E11000 duplicate key error index: draw.users.$email_1 dup key: { : "[email protected]" } code: 11000 n: 0 ok: 1

But it gives you enough to retrieve it.

You need to get the index that is causing the issue : "email_1" (use a regexp)

Then you need to ask the db about this index :

draw.users.getIndexKey("email_1")