0

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?

Dushyant Bangal
  • 6,048
  • 8
  • 48
  • 80
  • 1
    i don't see how that message came from that function since it always outputs `already exists` (among other things) – dandavis Jun 23 '16 at 06:11
  • No, thats the input to the function. the output is from 2nd character, till the field name: **11000 duplicate key error collection: mydatabase.mycollection index: myfield** and then **already exists** is appended – Dushyant Bangal Jun 23 '16 at 07:51
  • The answer here http://stackoverflow.com/questions/18032879/mongodb-difference-between-error-code-11000-and-11001 shows error message containing **.$** – Dushyant Bangal Jun 23 '16 at 07:54

0 Answers0