mongoose: How to get index name on duplicate document 11000 error?

How can I get the index for which the error occurs with?

e.g. if my index is named email, how do I get that from the err object?

About this issue

  • Original URL
  • State: closed
  • Created 10 years ago
  • Reactions: 1
  • Comments: 18 (1 by maintainers)

Most upvoted comments

Here is my RegExp solution to get index name with any type of error syntax I have found:

  var regex = /index\:\ (?:.*\.)?\$?(?:([_a-z0-9]*)(?:_\d*)|([_a-z0-9]*))\s*dup key/i,      
  match =  error.message.match(regex),  
  indexName = match[1] || match[2];  

Here what I have tested:

('E11000 duplicate key error collection: db.users index: name_1 dup key: { : "Kate" }').match(regex)[1]; // "name"
("E11000 duplicate key error index: myDb.myCollection.$id dup key: { : ObjectId('57226808ec55240c00000272') }").match(regex)[2] // "id"
('E11000 duplicate key error index: test.collection.$a.b_1 dup key: { : null }').match(regex)[1] // "b"
('E11000 duplicate key error collection: upsert_bug.col index: _id_ dup key: { : 3.0 }').match(regex)[1] // "_id"

Thanks to @paambaati I got the functionality I needed.

var user = new User(req.body);
  user.save(function(error) {
    if (error) {
      if (error.code === 11000) {
        // email or username could violate the unique index. we need to find out which field it was.
        var field = error.message.split(".$")[1];
        field = field.split(" dup key")[0];
        field = field.substring(0, field.lastIndexOf("_"));
        req.flash("errors", [{
          msg: "An account with this " + field + " already exists."
        }]);
        res.redirect("/join");
        return;
      }
      throw error;
    }
    req.flash("messages", "Thank you for joining.");
    res.redirect("/");
  });

But is there a terser way to get the same result? //cc @vkarpov15

Good job @alexbooker! There’s also another plugin for that, see #2284 and https://www.npmjs.com/package/mongoose-beautiful-unique-validation

The best way right now is by parsing the error message (slightly hacky, yes). The error message looks like:

E11000 duplicate key error index: test.x.$a_1 dup key: { : 1.0 }

Looks pretty consistent across mongodb server 2.4 and 2.6. The index: indicates which index causes the duplicate key error on the server side.