Mongoose -枚举字符串数组

iyzzxitl  于 2023-03-03  发布在  Go
关注(0)|答案(5)|浏览(143)

我有一个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" }

总之,我需要一个模式的属性,它具有一种字符串数组类型,可以根据预定义的值检查它的元素
实现这一目标的最有效方法是使用验证方法还是有更好的方法?

i5desfxk

i5desfxk1#

引自此处:

const SubStrSz = new mongoose.Schema({ value: { type: String, enum: ['qwerty', 'asdf'] } });
const MySchema = new mongoose.Schema({ array: [SubStrSz] });

使用该技术,您将能够验证数组中的值。

lpwwtiir

lpwwtiir2#

您可以尝试自定义验证?像这样

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']
  }
});

这是文档:https://mongoosejs.com/docs/validation.html

t0ybt7op

t0ybt7op3#

这里的distributers是distributerObj数组,同样你可以定义任何类型的对象。

const distributerObj = new Schema({
    "dis_id": {
        "type": "String"
    },
    "status": {
        "type": "String"
    }
});
const productSchema = new Schema({
    "distributers": {
        "type": [distributerObj]
    }
});
o4tp2gmn

o4tp2gmn4#

使用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}],
})
nhaq1z21

nhaq1z215#

使用nestjs而不创建子模式解决方案

export enum RolesEnum {
  User = 'user',
  Admin = 'admin'
}

...
export class User {
  ...
  @Prop({
    type: [String],
    enum: [RolesEnum.Admin, RolesEnum.User],
    default: []
  })
  roles: RolesEnum[]
  ...
}
...

相关问题