LearnBoost/mongoose — pull request #1571 by blakehaswell (2013-07-08 04:47:49+00:00)
Title: Added pre-save validation for unique indexes

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.