MEAN js has an error handler for mongo unique error. Here's the code:
var getUniqueErrorMessage = function(err) {
var output;
try {
var fieldName = err.err.substring(err.err.lastIndexOf('.$') + 2, err.err.lastIndexOf('_1'));
output = fieldName.charAt(0).toUpperCase() + fieldName.slice(1) + ' already exists';
} catch (ex) {
output = 'Unique field already exists';
}
return output;
};
From what I know, the aim to to find the name of field which is throwing the duplicate error.
However, there is no .$
in the error message, for which the code err.err.lastIndexOf('.$')
looks for in order to get the field name.
The error string is
E11000 duplicate key error collection: mydatabase.mycollection index: myfield_1 dup key: { : "asd" }
as there is no .$
in the string, index -1+2=1 is returned, which is beginning of string, and the whole dirty error message is sent:
11000 duplicate key error collection: mydatabase.mycollection index: myfield
So why does it search for .$
? Is there some significance of .$
? Right now i am using err.err.lastIndexOf('index: ') + 7
to get the index of field name.
Or does some other version of mongo include .$
in its error message?