在mongoose中添加多个validation

我有这个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 } }); 

这是我的validation“规则”

 var isNotTooShort = function(string) { return string && string.length >= 5; }; var onlyLettersAllow = function(string) { var myRegxp = /^[a-zA-Z]+$/i; return myRegxp.test(string); }; 

validation我的名字字段,我试过这个:

 userSchema.path('name').validate(isNotTooShort, 'Is too short'); userSchema.path('name').validate(onlyLettersAllow, 'Only Letters'); 

它的工作。 我可以在架构中的字段上添加多个validation吗? 就像是:

 validate:[onlyLettersAllow,isNotTooShort] 

       

网上收集的解决方案 "在mongoose中添加多个validation"

你可以添加像这样的多个validation:

 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 } });