Custom Error Messages Using Mongoose

So, according to mongoose docs , you should set up a custom error message in the schema as follows:

var breakfastSchema = new Schema({ eggs: { type: Number, min: [6, 'Too few eggs'], max: 12 }, bacon: { type: Number, required: [true, 'Why no bacon?'] } }); 

So, I wanted to do something like this:

 var emailVerificationTokenSchema = mongoose.Schema({ email: {type: String, required: true, unique: [true, "email must be unique"]}, token: {type: String, required: true}, createdAt: {type: Date, required: true, default: Date.now, expires: '4h'} }); 

The idea is that when you try to save one of these tokens, and there is already a conflict, he deflates an error message stating that "the letter must be unique."

However, when I do something like this (where I save the token with the same email address):

 verificationToken.save( function (err) { if (err) { return console.log(err); } else { return console.log(err); } }); 

I keep getting the following:

 'E11000 duplicate key error: index ___.emailVerificationToken.$email_1 dup key: { : " _____@wdad.com 

Any thoughts? Unique parameter not supported for custom messages? Is this a viable way to go about things?

+10
source share
5 answers

Unique parameter not supported for custom messages?

Uniqueness in Mongoose is not a validation parameter (e.g. required ); he tells Mongoose to create a unique index in MongoDB for this field.

The uniqueness constraint is fully processed on the MongoDB server. When you add a document with a duplicate key, the MongoDB server will return the error you are displaying ( E11000... ).

You must handle these errors yourself if you want to create personalized error messages. The Mongoose documentation (search for โ€œError Intermediate Toolโ€) provides you with an example of creating custom error handling:

 emailVerificationTokenSchema.post('save', function(error, doc, next) { if (error.name === 'MongoError' && error.code === 11000) { next(new Error('email must be unique')); } else { next(error); } }); 

(although this does not give you a specific field for which it was not possible to limit uniqueness)

+13
source

This is not possible right away as you tried it, but you can take a look at the mongoose-unique-validator , which allows you to customize the error message if the uniqueness would be violated.

In particular, you are interested in the section on user errors .

To get what you want

"email must be unique"

he will be like this

 var uniqueValidator = require('mongoose-unique-validator'); ... emailVerificationTokenSchema.plugin(uniqueValidator, { message: '{PATH} must be unique' }); 
+4
source
 verificationToken.save( function (err) { if (err) { return res.status(400).send({ message: (err.name === 'MongoError' && err.code === 11000) ? 'Email already exists !' : errorHandler.getErrorMessage(err) }); } else { return console.log('No Error'); } }); 
0
source

Updated version for Mongoose 5.xx

 MySchema.post('save', function (error, doc, next) { if (err.name === 'BulkWriteError' && error.code === 11000) next(new Error('This item already exists, please try again')); else next(error); }); 
0
source

You can rewrite error messages in the source, as well as in the node modules. Here is the way to go: YOUR_PROJECT / node_modules / mongoose / lib / error / validation.js

then you have no problem with the extra package for this.

0
source

All Articles