Mongoose, MongoError hanlding

I am creating a simple application using mongoose to interact with MongoDb and the unique validation error handling has been bothering me a lot.

UserSchema = new Schema({
                        email: {type:String, required: true, unique: true, trim: true, match: [emailRegex, 'Email format is invalid']},
                        hashedPassword: {type: String, default: ''},
                        salt: {type: String, required: true, unique:true}

                    }
);

In the schema above, I have unique :true for email and when a new document with a duplicate email address is input, the error I recieve is:

{ [MongoError: insertDocument :: caused by :: 11000 E11000 duplic
ndex: testdb.users.$email_1  dup key: { : "minhs22sa22f@gmail.com
  name: 'MongoError',
  code: 11000,
  err: 'insertDocument :: caused by :: 11000 E11000 duplicate key
estdb.users.$email_1  dup key: { : "minhs22sa22f@gmail.com" }' }

The error object above take quite some effort to extract information from them to display back to client, so my question is: Is there anyway to have it use the validationError instead, those are more intuitive and simpler?

I has considered using custom path validation as well but it is better to use the built-in functionality if possible.

Many thanks,

Not really. The error is a unique key violation on the email field and is emitted by MongoDB. In order to make this a validation error, the validation function would have to discover the unique key violation on its own. There's basically two ways this could happen in a validation function:

  1. query MongoDB, get the above error, and parse it into a validationError
  2. remember all the emails so you can check for unique key violations yourself

The first method just pushes the parsing into a validation function and uses an extra MongoDB query for no gain. The second doesn't doesn't make sense.

Write a function that parses the error into whatever useful form you need. It only has to be written and tested once.

Another possibility I've found is to use an mom module that converts the duplicate key error into a Validation like one.

This one is called mongoose-unique-validator

I've not read the code but my guess is it is only parsing the error in order to reformat it.

Also, I would look at the performance, there is good chance it could affect it.