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?
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.
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.
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.
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With