6

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?

0

5 Answers 5

5

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];
1
  • I added a .trim() because I had some space before the index name
    – Hugo H
    Commented Aug 22, 2019 at 20:03
4

I use a regular expression. Like this

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

Which is totally hacky but is working for me.

1
  • 1
    Does not work on compound indexes like this: $client_1_email_1 Commented Feb 10, 2015 at 12:18
3

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
0

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

4
  • You'd want to only do the find on indexed fields which were unique. It would require searching multiple fields potentially. Commented Jul 9, 2013 at 13:03
  • Thanks both of you. I'll guess I'll try findOne then before I do the save. Thought I could get away with using mongoError message. And I guess that should be possible in some way? The message tells me what I want, but as a string, that would be messy to do a regexp on I guess.
    – oivind
    Commented Jul 9, 2013 at 13:18
  • @oivind There'd still be a chance that the update would fail as another document could be saved between the call to findOne and the insert/update. Commented Jul 9, 2013 at 13:46
  • depends on the library you use, some give detailed errors, some just 1 or 0. I use native mongo lib but I don't think is any more detailed than yours.
    – Discipol
    Commented Jul 9, 2013 at 17:31
0

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.