One of the most important aspects of the mongoose
module is validation against a defined model. Mongoose provides a built-in validation framework that only requires you to define validation functions to perform on specific fields that need to be validated. When you try to create a new instance of a document, read a document from the database or save a document, the validation framework calls your custom validation methods and returns an error if the validation fails.
The validation framework is actually very simple to implement. You call the validate()
method on the specific path in the Model
object that you want to apply validation to and pass in a validation function. The validation function accepts the value of the field and then uses that value to return true
or false
, depending on whether the value is valid. The second parameter to the validate()
method is an error
string that is applied to the error object if validation fails. For example:
Words.schema.path('word').validate(function(value){
return value.length < 20;
}, "Word is Too Big");
The error object thrown by validation has the following fields:
error.errors.<field>.message: String defined when adding the validate function
error.errors.<field>.type: Type of validation error
error.errors.<field>.path: Path in the object that failed validation
error.errors.<field>.value: Value that failed validation
error.name: Error type name
err.message: Error message
Listing 16.11 shows a simple example of adding validation to the word model where a word of length 0 or greater than 20 is invalid. Notice that when the newWord
is saved in line 18, an error is passed to the save()
function. The output in lines 12–26 shows the various values of different parts of the error, as shown in Figure 16.11. You can use these values to determine how to handle validation failures in the code.
01 var mongoose = require('mongoose'),
02 var db = mongoose.connect('mongodb://localhost/words'),
03 var wordSchema = require('./word_schema.js').wordSchema;
04 var Words = mongoose.model('Words', wordSchema);
05 Words.schema.path('word').validate(function(value){
06 return value.length > 0;
07 }, "Word is Too Small");
08 Words.schema.path('word').validate(function(value){
09 return value.length < 20;
10 }, "Word is Too Big");
11 mongoose.connection.once('open', function(){
12 var newWord = new Words({
13 word:'supercalifragilisticexpialidocious',
14 first:'s',
15 last:'s',
16 size:'supercalifragilisticexpialidocious'.length,
17 });
18 newWord.save(function (err) {
19 console.log(err.errors.word.message);
20 console.log(String(err.errors.word));
21 console.log(err.errors.word.type);
22 console.log(err.errors.word.path);
23 console.log(err.errors.word.value);
24 console.log(err.name);
25 console.log(err.message);
26 mongoose.disconnect();
27 });
28 });