I have this Schema:
var userSchema = new mongoose.Schema({
name: {type: String,required: true,lowercase: true, trim: true},
email: {type: String, required : true, validate: validateEmail },
createdOn: { type: Date, default: Date.now },
lastLogin: { type: Date, default: Date.now }
});
and this are my validation "rules"
var isNotTooShort = function(string) {
return string && string.length >= 5;
};
var onlyLettersAllow = function(string) {
var myRegxp = /^[a-zA-Z]+$/i;
return myRegxp.test(string);
};
To validate my name field I tried this:
userSchema.path('name').validate(isNotTooShort, 'Is too short');
userSchema.path('name').validate(onlyLettersAllow, 'Only Letters');
and it works. Can I add multiple validation on a field in Schema? Something like:
validate:[onlyLettersAllow,isNotTooShort]
Mongoose registers validation as a pre('save') hook on every schema by default. You can disable automatic validation before save by setting the validateBeforeSave option. You can manually run validation using doc. validate(callback) or doc.
mongoose-unique-validator is a plugin which adds pre-save validation for unique fields within a Mongoose schema. This makes error handling much easier, since you will get a Mongoose validation error when you attempt to violate a unique constraint, rather than an E11000 error from MongoDB.
The __v field is called the version key. It describes the internal revision of a document.
Mongoose provides several built-in validators such as required, minlength, maxlength, min, and max. These built-in validators are very useful and simple to configure.
You can add more than one validation like this:
var manyValidators = [
{ validator: isNotTooShort, msg: 'Is too short' },
{ validator: onlyLettersAllow, msg: 'Only Letters' }
];
var userSchema = new Schema({
name: { type: String, validate: manyValidators },
email: {type: String, required : true, validate: validateEmail },
createdOn: { type: Date, default: Date.now },
lastLogin: { type: Date, default: Date.now }
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With