猫鼬扩展默认验证 [英] Mongoose expand default validation
问题描述
我想在猫鼬模式验证规则中构建"minLength"和"maxLength",当前解决方案是:
I want to build "minLength" and "maxLength" in the mongoose schema validation rules, the current solution is:
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'));
});
但是我认为应该通过添加如下这样的自定义架构规则来简化此操作:
However I think this should be simplified by just adding custom schema rules like so:
var blogSchema = new Schema({
title: {
type: String,
required: true,
minLength: 8,
maxLength: 32
}
});
我该怎么办,这有可能吗?
How can I do this, is this even possible?
推荐答案
检出库 mongoose-validator .它以与您描述的非常相似的方式集成了node-validator库,以便在猫鼬模式中使用.
Check out the library mongoose-validator. It integrates the node-validator library for use within mongoose schemas in a very similar way to which you have described.
具体来说, node-validator len 或 min 和 max 方法应提供您所需的逻辑.
Specifically, the node-validator len or min and max methods should provide the logic you require.
尝试:
var validate = require('mongoose-validator').validate;
var blogSchema = new Schema({
title: {
type: String,
required: true,
validate: validate('len', 8, 32)
}
});
这篇关于猫鼬扩展默认验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!