Full-Stack Web Development with Vue.js and Node

(singke) #1
Introducing MongoDB Chapter 3

As you can see, we have changed the value of the name key to an object instead of just a
string. Here, we can add as many validations as we want. So, the added validation


required: true checks if there is some value set on the name and email of the user before


saving that document in the collection. It returns an error if the validation is not met.


We can also pass a message when the validation returns an error. For example:


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

var UserSchema = new Schema({
name: {
required: [true, 'Let us know you by adding your name!']
},
email: {
required: [true, 'Please add your email as well.']
}
});

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

This way, we can also customize the messages as per our requirements. Very cool, right?


Type validation

The type validation method defines the types of fields in a document. The different


variations of type can be String, boolean, and number.


String

The string itself has several validators under it, such as enum, match, maxlength, and


minlength.


maxlength and minlength define the length of a string.


Numbers

Numbers have two validators: min and max. The min and max values define the range of


values for a field in a collection.

Free download pdf