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];
Sign up to request clarification or add additional context in comments.

1 Comment

I added a .trim() because I had some space before the index name
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 Comment

Does not work on compound indexes like this: $client_1_email_1
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]})!`;
};

Comments

0

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

4 Comments

You'd want to only do the find on indexed fields which were unique. It would require searching multiple fields potentially.
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 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.
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.
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")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.