【问题标题】:How can i validate type in mongoose custom validator我如何验证猫鼬自定义验证器中的类型
【发布时间】:2017-05-03 00:03:16
【问题描述】:
key: {
type: 'String',
required: [true, 'Required'],
trim: true
}
每当我使用自定义验证器对其进行验证时,它都会转换为“字符串”,即
导致始终有效的类型。
像“key”应该只接受“String”,如果“Number”应该抛出验证而不是强制转换。
【问题讨论】:
标签:
javascript
mongodb
validation
mongoose
mongoose-schema
【解决方案1】:
(对于那些还在纠结这个问题的人)
您可以为此创建一个custom schema type,它不允许强制转换。然后你可以在你的架构中使用它而不是字符串(例如type: NoCastString)。
function NoCastString(key, options) {
mongoose.SchemaType.call(this, key, options, "NoCastString");
}
NoCastString.prototype = Object.create(mongoose.SchemaType.prototype);
NoCastString.prototype.cast = function(str) {
if (typeof str !== "string") {
throw new Error(`NoCastString: ${str} is not a string`);
}
return str;
};
mongoose.Schema.Types.NoCastString = NoCastString;
【解决方案2】:
您可以将验证函数传递给猫鼬模式的验证器对象。
请参阅下面具有自定义验证功能以验证电话号码架构的示例架构。
var userSchema = new Schema({
phone: {
type: String,
validate: {
validator: function(v) {
return /\d{3}-\d{3}-\d{4}/.test(v);
},
message: '{VALUE} is not a valid phone number!'
},
required: [true, 'User phone number required']
}
});
这个验证可以通过断言来测试
var User = db.model('user', userSchema);
var user = new User();
var error;
user.phone = '555.0123';
error = user.validateSync();
assert.equal(error.errors['phone'].message,
'555.0123 is not a valid phone number!');
你可以有自己的正则表达式来匹配你想要的字符串应该是什么模式。