Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error codes for Mongoose validation? #3059

Closed
manikandants opened this issue Jun 10, 2015 · 2 comments
Closed

Error codes for Mongoose validation? #3059

manikandants opened this issue Jun 10, 2015 · 2 comments

Comments

@manikandants
Copy link

For unique field validation we get error message as follows

{ [MongoError: insertDocument :: caused by :: 11000 E11000 duplicate key error index: test.users.$phone_1 dup key: { : 9876543210.0 }]
name: 'MongoError',
message: 'insertDocument :: caused by :: 11000 E11000 duplicate key error index: test.users.$phone_1 dup key: { : 9876543210.0 }',
index: 0,
code: 11000,
errmsg: 'insertDocument :: caused by :: 11000 E11000 duplicate key error index: test.users.$phone_1 dup key: { : 9876543210.0 }' }

For required field validation the error is as follows.

{ [ValidationError: User validation failed]
message: 'User validation failed',
name: 'ValidationError',
errors:
{ email:
{ [ValidatorError: Path email is required.]
properties: [Object],
message: 'Path email is required.',
name: 'ValidatorError',
kind: 'required',
path: 'email',
value: undefined } } }

The interesting part in first error is the error.code as 11000 which can be directly compared to identify the error.
Wouldn't it be nice to have either predefined or customized error code for each of these error kind?
for example 91000 for 'required', 91001 for 'length' etc

@vkarpov15
Copy link
Collaborator

Unique is not a mongoose validator, it creates mongodb unique index on the mongodb server, because mongoose can't effectively verify unique constraints in the general case. Validation errors have a 'kind' that you can use to check the error type for a given field, which seems to be the answer to your question.

If you're looking to get more friendly MongoErrors, @MattouFP wrote a plugin https://www.npmjs.com/package/mongoose-beautiful-unique-validation (see #2284 (comment))

@manikandants
Copy link
Author

Thanks @vkarpov15 :) That answers my question. I was looking for a common error kind/code for all errors. Using @MattouFP plugin will give errors with 'kind' and solve my issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants