我有一个架构,其属性具有预定义的字符串数组类型。
这就是我尝试做的:
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方法还是有更好的方法?
引用自这里:
const SubStrSz = new mongoose.Schema({ value: { type: String, enum: ['qwerty', 'asdf'] } });
const MySchema = new mongoose.Schema({ array: [SubStrSz] });
使用该技术,您将能够验证数组内的值。
您可以尝试自定义验证吗?像这样
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']
}
});
使用nestjs无需创建子模式解决方案
export enum RolesEnum {
User = 'user',
Admin = 'admin'
}
...
export class User {
...
@Prop({
type: [String],
enum: [RolesEnum.Admin, RolesEnum.User],
default: []
})
roles: RolesEnum[]
...
}
...
这里的分发者将是
distributerObj
的数组,类似地你可以定义任何类型的对象。
const distributerObj = new Schema({
"dis_id": {
"type": "String"
},
"status": {
"type": "String"
}
});
const productSchema = new Schema({
"distributers": {
"type": [distributerObj]
}
});
使用 ref 与定义的枚举模式建立关系
const actionsEnums = new Mongoose.Schema({value: { type: String, enum:["account-deletion","account-update"]}});
const Privilege = new Mongoose.Schema(
{
userLevel: { type: String, required: true },
actions: [{type: String, refs: actionsEnums}],
})
你可以试试这个
const InterestSchema = new Schema({
interests: {
type: [{
enum: ['which', 'ever', 'values', 'allowed'],
]}
}
})
希望这有帮助