Mongoose Duplicate Errors
Custom error messages for the mongodb duplicate error
Installation
yarn add mongoose-duplicate-error
Usage
Just add it to a model and it will prettify the unique errors by default, by transforming the
E11000 duplicate key error collection...
error into a other must be unique
validation error.
const Schema = Schema;const mongooseDuplicateError = ; const CustomerSchema = username: type: String unique: true email: type: String unique: true ; CustomerSchema;
It will also work for compound indexes, by generating an error for the first index in the group
const Schema = Schema;const mongooseDuplicateError = ; const CustomerSchema = email: required: true type: String deleted: Boolean; CustomerSchemaindex email: 1 deleted: 1 unique: true ;CustomerSchema;
You can further custumize the error messages for any unique index. By providing a "path" and message template you can specify exactly which field will recieve an error, and with what text.
const Schema = Schema;const mongooseDuplicateError = ; const CustomerSchema = email: required: true type: String deleted: Boolean; CustomerSchemaindex email: 1 deleted: 1 unique: true ;CustomerSchema;