Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb duplicate key error. How do i get the error field from the error object as object?

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?

like image 383
oivind Avatar asked Jul 09 '13 11:07

oivind


People also ask

How do I catch a MongoDB error?

For MongoDB, there is an internal system of error classification. MongoDB assigns different names and codes to errors that can be seen by console logging an error. By console logging the errors, you can see what the error stacktrace (the error metadata and where it occurs in your app) looks like.

How do I handle e11000 duplicate key error?

The simplest way to get some game logic running only when the e11000 error is thrown would be to use a try-catch. You can send whatever unique error key you want back to your client-code with the Sparks. setScriptError() function.

How do I fix a duplicate key collection?

If there is more than one document without a value for the indexed field or is missing the indexed field, the index build will fail with a duplicate key error. You can combine the unique constraint with the sparse index to filter these null values from the unique index and avoid the error.


1 Answers

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];
like image 52
olyjosh Avatar answered Sep 22 '22 01:09

olyjosh