I'm trying to decide how I want to handle validation errors in Mongoose.
Custom error messages using node-validator
I have defined my own validation rules using node-validator, for example:
UserSchema.path('username')
.validate(function (username) {
return validator.check(username).notEmpty()
}, 'Username cannot be blank')
Which will generate an error that looks like this:
username:
{ message: 'Validator "Username cannot be blank" failed for path username',
name: 'ValidatorError',
path: 'username',
type: 'Username cannot be blank' },
Using mongoose-validator
However, node-validator provides its own error messages. If I use the mongoose-validator Node module to plug node-validator directly into my schema, then I can use these error messages directly instead:
var UserSchema = new Schema({
name: { type: String, validate: [validate('notEmpty')] }
});
Which will generate an error message that looks like:
name:
{ message: 'Validator "String is empty" failed for path name',
name: 'ValidatorError',
path: 'name',
type: 'String is empty' } }
I can also provide a custom error message here too:
var UserSchema = new Schema({
name: { type: String, validate: [validate({message: 'Name cannot be blank' }, 'notEmpty')] }
});
Mongoose required
flag
Mongoose lets you define a field as required:
var UserSchema = new Schema({
name: { type: String, required: true }
});
Which will generate an error message that looks like:
name:
{ message: 'Validator "required" failed for path name',
name: 'ValidatorError',
path: 'name',
type: 'required' } }
The question
It feels as if these validators want you to use their built-in error messages. For instance, I want to declare a field as required
as seen above, but I can't find a way of customising the error message. And the mongoose-validator module did not support custom messages up until very recently, which makes me think they are an anti-pattern at the model level.
What's the best way to implement these validators? Should I let them generate their own errors and then somehow interpret them afterwards?
next()
. – thanpolas