我想在mongoose模式验证规则中构建“minLength”和“maxLength”,目前的解决方案是:
var blogSchema = new Schema({
title: { required: true, type: String }
});
blogSchema.path('title').validate(function(value) {
if (value.length < 8 || value.length > 32) return next(new Error('length'));
});
但是我想这应该通过添加自定义架构规则来简化:
var blogSchema = new Schema({
title: {
type: String,
required: true,
minLength: 8,
maxLength: 32
}
});
我怎么能这样做,这甚至可能吗?
解决方法:
查看库mongoose-validator.它集成了node-validator库,以便在mongoose模式中使用,其方式与您描述的方式非常相似.
具体来说,node-validator len或min和max方法应该提供您需要的逻辑.
试试:
var validate = require('mongoose-validator').validate;
var blogSchema = new Schema({
title: {
type: String,
required: true,
validate: validate('len', 8, 32)
}
});