@@ -74,7 +74,6 @@ function SchemaType(path, options, instance) {
7474 this . options = new Options ( options ) ;
7575 this . _index = null ;
7676
77-
7877 if ( utils . hasUserDefinedProperty ( this . options , 'immutable' ) ) {
7978 this . $immutable = this . options . immutable ;
8079
@@ -447,21 +446,38 @@ SchemaType.prototype.index = function(options) {
447446 *
448447 * _NOTE: violating the constraint returns an `E11000` error from MongoDB when saving, not a Mongoose validation error._
449448 *
450- * @param {Boolean } bool
449+ * You can optionally specify an error message to replace MongoDB's default `E11000 duplicate key error` message.
450+ * The following will throw a "Email must be unique" error if `save()`, `updateOne()`, `updateMany()`, `replaceOne()`,
451+ * `findOneAndUpdate()`, or `findOneAndReplace()` throws a duplicate key error:
452+ *
453+ * ```javascript
454+ * new Schema({
455+ * email: {
456+ * type: String,
457+ * unique: [true, 'Email must be unique']
458+ * }
459+ * });
460+ * ```
461+ *
462+ * Note that the above syntax does **not** work for `bulkWrite()` or `insertMany()`. `bulkWrite()` and `insertMany()`
463+ * will still throw MongoDB's default `E11000 duplicate key error` message.
464+ *
465+ * @param {Boolean } value
466+ * @param {String } [message]
451467 * @return {SchemaType } this
452468 * @api public
453469 */
454470
455- SchemaType . prototype . unique = function ( bool ) {
471+ SchemaType . prototype . unique = function unique ( value , message ) {
456472 if ( this . _index === false ) {
457- if ( ! bool ) {
473+ if ( ! value ) {
458474 return ;
459475 }
460476 throw new Error ( 'Path "' + this . path + '" may not have `index` set to ' +
461477 'false and `unique` set to true' ) ;
462478 }
463479
464- if ( ! this . options . hasOwnProperty ( 'index' ) && bool === false ) {
480+ if ( ! this . options . hasOwnProperty ( 'index' ) && value === false ) {
465481 return this ;
466482 }
467483
@@ -471,7 +487,10 @@ SchemaType.prototype.unique = function(bool) {
471487 this . _index = { type : this . _index } ;
472488 }
473489
474- this . _index . unique = bool ;
490+ this . _index . unique = ! ! value ;
491+ if ( typeof message === 'string' ) {
492+ this . _duplicateKeyErrorMessage = message ;
493+ }
475494 return this ;
476495} ;
477496
@@ -1743,6 +1762,14 @@ SchemaType.prototype.getEmbeddedSchemaType = function getEmbeddedSchemaType() {
17431762 return this . $embeddedSchemaType ;
17441763} ;
17451764
1765+ /*!
1766+ * If _duplicateKeyErrorMessage is a string, replace unique index errors "E11000 duplicate key error" with this string.
1767+ *
1768+ * @api private
1769+ */
1770+
1771+ SchemaType . prototype . _duplicateKeyErrorMessage = null ;
1772+
17461773/*!
17471774 * Module exports.
17481775 */
0 commit comments