Validation

Mongoose comes with several built-in validators. Some validators are present in all data types and some are exclusive for a data type. For example, a String field will have the min and max validators but a Boolean type will not.

Let's add some validations to our Team schema. Open the mongoose-connection.js file and apply the following changes:

...
const TeamSchema = new mongoose.Schema({
name: {
type: String,
min: 3,
max: 100,
required: true,
unique: true
},
ranking: {
type: Number,
min: 1
},
captain: {
type: String,
required: true
},
Trainer: {
type: String,
required: true
},
confederation: {
type: String,
required: true,
uppercase: true
}
})

Now, our schema looks more professional and will help us validate the data before it is persisted in MongoDB. Most of the validators are self-explanatory. As you might have noticed, when you want to apply validators, the syntax to declare a field changes a little bit; in this case, a JavaScript object should be passed to define the data type and validators. To find more information about validators, visit http://mongoosejs.com/docs/validation.html.

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

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