mongoose-unique-validation
This is a fork from matteodelabre/mongoose-beautiful-unique-validation. The difference is that mongoose-unique-validator also validates the Model.update method.
Plugin for Mongoose that turns duplicate errors into regular Mongoose validation errors.
Mongoose's unicity constraint actually relies on MongoDB's unique
indexes.
It means that, if you have a schema like this one:
mongoose;
Duplicates will be reported with this kind of error:
This is not the same kind of error as normal Validation errors, so you need to handle that as a special case―and special cases allow room for bugs. This plugin solves this problem by turning driver-level duplicate errors (E11000 and E11001) into regular Validation errors.
Install
npm install --save mongoose-beautiful-unique-validation
Supported versions of Mongoose
The 5.0.0 versions of this module only support Mongoose 4.5.0 and upper. If you need to use previous versions of Mongoose, use the 4.0.0 versions.
Supported versions of Node
The latest version of this module supports Node.js
version 6.*
, 5.*
, 4.*
, 0.12.*
and 0.10.*
.
If you find a bug while using one of these versions, you can
fill a bug report
and we will take care of it as soon as possible!
Example
Saving a duplicate document
let beautifyUnique = ;let userSchema = mongoose; // enables beautifyinguserSchema; // let's create two conflicting documentslet User = mongoose;let admin1 = name: 'admin'; let admin2 = name: 'admin'; admin1 ; admin2 ; // will print:// Success saving admin1!// admin2 could not be saved: [ValidationError: User validation failed]
Updating a document to be a duplicate
let beautifyUnique = ;let userSchema = mongoose; // enables beautifyinguserSchema; // let's create two documentslet User = mongoose;let admin1 = name: 'admin1'; let admin2 = name: 'admin2'; // first, save both documentsPromiseall admin1 admin2; // will print:// admin2 could not be updated: [ValidationError: User validation failed]
Usage
Schemata that will produce beautified errors need to be plugged
in with this module using the .plugin()
method. You can also
use it as a global plugin.
You need to plug in this module after declaring all indexes on the schema, otherwise they will not be beautified.
By default, the ValidatorError
message will be
Validator failed for path xxx with value xxx
.
If you want to override it, add your custom message in the unique
field (instead of true
), during the schema's creation.
The error's errors
property contain a list of all original
values that made the contraint fail. This property is not
filled in when using findOneAndUpdate
.
License
Released under the MIT license.
See the full license text.