Built-in validation

One of the core concepts of Mongoose is that it enforces a schema on top of a
schema-less design, such as MongoDB. In doing so, we gain a number of new features, including built-in validation. By default, every schema type has a built-in required validator available. Furthermore, numbers have both min and max validators, and strings have enumeration and matching validators. Custom validators can also be defined via your schemas. Let's take a brief look at some validation added to our example schema from earlier:

var Account = new Schema({
username: { type: String, required: true },
date_created: { type: Date, default: Date.now },
visits: { type: Number, default: 0 },
active: { type: Boolean, default: false },
age: { type: Number, required: true, min: 13, max: 120 }
});

The validation we added to our schema is that the username parameter is now required, and we included a new field called age, which is a number that must be between 13 and 120 (years). If either value doesn't match the validation requirements (that is, the username is blank or the age is less than 13 or greater than 120), an error will be thrown.

Validation will fire automatically whenever a model's .save() function is called; however, you can also manually validate by calling a model's .validate() function with a callback to handle the response. Building on the example, add the following code, which will create a new mongoose model from the schema defined:

var AccountModel = mongoose.model('Account', Account);
var newUser = new AccountModel({ username: 'randomUser', age: 11 });
newUser.validate(function(err) {
console.log(err);
});
// the same error would occur if we executed:
// newUser.save();

Running the preceding code should log the following error to the screen:

{
message: 'Validation failed',
name: 'ValidationError',
errors: {
age: {
message: 'Path '
age ' (11) is less than minimum allowed value (13).',
name: 'ValidatorError',
path: 'age',
type: 'min',
value: 11
}
}
}

You can see that the error object that is returned from validate is pretty useful and provides a lot of information that can help when validating your model and returning error messages back to the user.

Validation is a very good example of why it's so important to always accept an error object as the first parameter to any callback function in Node. It's equally important that you check the error object and handle it appropriately.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.136.142