Full-Stack Web Development with Vue.js and Node

(singke) #1
Introducing MongoDB Chapter 3

Default validations


Let's talk about some of the default validations that Mongoose provides us with. These are


also called built-in validators.


required()

The required() validator checks if the field we added this validation on has some value


or not. Previously, in the User model, we had this code:


var mongoose = require("mongoose");
var Schema = mongoose.Schema;

var UserSchema = new Schema({
name: String,
email: String
});

var User = mongoose.model("User", UserSchema);
module.exports = User;

This code also has a validation associated with the fields of the user. It requires the name
and email of a user to be a string and not numbers, or Boolean, or anything else. But this


code doesn't make sure the name and email fields are set for the user.


So, if we want to add a required() validation, the code should be modified in this way:


var mongoose = require("mongoose");
var Schema = mongoose.Schema;

var UserSchema = new Schema({
name: {
required: true
},
email: {
required: true
}
});

var User = mongoose.model("User", UserSchema);
module.exports = User;
Free download pdf