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

Added pre-save validation for unique indexes #1571

Closed
wants to merge 1 commit into from

Conversation

blakehaswell
Copy link

Currently unique fields are not validated by Mongoose pre save, rather the save is simply attempted and it is left up to MongoDB to throw an E11000 error.

That behaviour makes elegant error handling difficult (as noted in Issue #1225).

This patch fixes that by adding a pre-save validator which queries the DB for duplicate records and throws a validation error if it finds any. You can now handle these errors as you would with any other validation error:

if (err.errors.email.type === 'duplicate') {
    doSomething();
}

As a note, this patch will slow down write performance, but I feel that for most cases the more consistant error handling is worth the performance hit. Possibly we could add a configuration flag to allow people to turn this pre-save check off for applications where write performance is critical.

…pass a validation error instead of failing with an E11000 error.
@aheckmann
Copy link
Collaborator

While we appreciate the work here, this is best left as a plugin since not everyone would like this behavior.

@aheckmann aheckmann closed this Jul 8, 2013
@blakehaswell
Copy link
Author

Noted. In that case I’ve published a plugin which accomplishes the same behaviour:
https://github.com/blakehaswell/mongoose-unique-validator

@aheckmann
Copy link
Collaborator

great!

@faceleg
Copy link

faceleg commented Jul 10, 2013

I appreciate the work! I do also appreciate that it is kept out of Mongoose for now. Thanks @aheckmann & @blakehaswell

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

Successfully merging this pull request may close these issues.

3 participants