Added pre-save validation for unique indexes #1571
Closed
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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:
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.