我有一个Schema,它有一个预定义的字符串数组类型的属性。
这就是我一直在努力做的:
interests: {
type: [String],
enum: ['football', 'basketball', 'read'],
required: true
}
问题是,当我试图输入一个错误的值,而不是在枚举上定义的值时,数组不会用枚举列表来验证它。
例如,它应该通过而不应该通过:
{ "interests": ["football", "asdf"] }
因为"asdf"
不是在枚举列表中预定义的,所以它不应该通过验证,但不幸的是,它通过了验证并保存了它。
我试过用一个字符串类型的值来代替一个字符串数组来检查这个东西,它工作了。
例如:
interests: {
type: String,
enum: ['football', 'basketball', 'read'],
required: true
}
例如,这是预期的失败:
{ "interest": "asdf" }
总之,我需要一个模式的属性,它具有一种字符串数组类型,可以根据预定义的值检查它的元素
实现这一目标的最有效方法是使用验证方法还是有更好的方法?
5条答案
按热度按时间i5desfxk1#
引自此处:
使用该技术,您将能够验证数组中的值。
lpwwtiir2#
您可以尝试自定义验证?像这样
这是文档:https://mongoosejs.com/docs/validation.html
t0ybt7op3#
这里的distributers是
distributerObj
数组,同样你可以定义任何类型的对象。o4tp2gmn4#
使用ref与定义的枚举模式建立关系
nhaq1z215#
使用nestjs而不创建子模式解决方案