2

I have user schema with 2 unique fields(email and username) and when i try to create new user with duplicated field I have that error

{
  "error": {
    "code": 11000,
    "index": 0,
    "errmsg": "E11000 duplicate key error collection: InstaClone.users index: email_1 dup key: { : \"baidario.ua@gmail.com\" }",
    "op": {
      "hashedPassword": "$2a$10$eaMym5AMibJlGOSBV3/DHOXPhSoMMDTNwxGcSOn4tEPg07htyQ2Ey",
      "email": "baidario.ua@gmail.com",
      "username": "baidario",
      "fullName": "Roman Baida",
      "_id": "58d3a8acdc57641e30e9027a",
      "created": "2017-03-23T10:50:49.188Z",
      "__v": 0
    }
  }
}

How I can get duplicated filed name? Only way I see is to parse errmsg field. Maybe someone know better way?

  • 1
    before inserting the new user, just run a query like db.users.find({$or: [{"username": username}, {"email": email}}). if it does return a document, then username or email are already present in db – felix Mar 23 '17 at 11:14
  • 2
    @felix that solution has a race-condition, in which a new user could get created between the time the `find()` returns and the `create()` is executed (resulting in the duplicate key error). – robertklep Mar 23 '17 at 11:17

1 Answers1

3

To customize error returned from mongoose unique validation you can use package called: mongoose-beautiful-unique-validation

https://www.npmjs.com/package/mongoose-beautiful-unique-validation

kaxi1993
  • 4,535
  • 4
  • 29
  • 47
  • 4
    Alternatively, see [this answer](http://stackoverflow.com/a/30594137/893780) on how to "catch" E11000 errors. – robertklep Mar 23 '17 at 11:20