MikeNQ
MikeNQ

Reputation: 653

Mongoose, MongoError handling

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 receive is:

{ [MongoError: insertDocument :: caused by :: 11000 E11000 duplic
ndex: testdb.users.$email_1  dup key: { : "[email protected]
  name: 'MongoError',
  code: 11000,
  err: 'insertDocument :: caused by :: 11000 E11000 duplicate key
estdb.users.$email_1  dup key: { : "[email protected]" }' }

The error object above takes 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.

Upvotes: 0

Views: 1475

Answers (2)

jhenriquez
jhenriquez

Reputation: 180

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.

Upvotes: 0

wdberkeley
wdberkeley

Reputation: 11671

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.

Upvotes: 1

Related Questions