我有一个架构,该架构的属性与预定义的字符串数组的类型相同。
这是我尝试做的事情:
interests: {
type: [String],
enum: ['football', 'basketball', 'read'],
required: true
}
问题是,当我尝试输入未在枚举中定义的错误值时,将无法使用枚举列表对其进行验证。
例如,这会通过,它不应该通过:
{ "interests": ["football", "asdf"] }
由于"asdf"
在枚举列表中未预定义,因此不应通过验证,但是不幸的是,它已通过验证并保存。
我尝试使用字符串类型的值而不是字符串数组来检查该问题,并且可以正常工作。
例如:
interests: {
type: String,
enum: ['football', 'basketball', 'read'],
required: true
}
例如,这失败了:
{ "interest": "asdf" }
最后,我需要一个模式属性,该属性具有一串字符串,可以根据预定义的值检查其元素
达到此目标的最有效方法是使用validate方法,还是有更好的方法?
答案 0 :(得分:1)
报价:https://github.com/Automattic/mongoose/issues/6102#issuecomment-364129706
const SubStrSz = new mongoose.Schema({value:{type:String,enum:['qwerty','asdf']}});; const MySchema = new mongoose.Schema({array:[SubStrSz]});
使用该技术,您将能够验证数组内部的值。
答案 1 :(得分:0)
您可以尝试自定义验证吗?
const userSchema = new Schema({
phone: {
type: String,
validate: {
validator: function(v) {
return /\d{3}-\d{3}-\d{4}/.test(v);
},
message: props => `${props.value} is not a valid phone number!`
},
required: [true, 'User phone number required']
}
});