2
votes

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 dbfelix
@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

1 Answers

3
votes

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