Mongoose - 枚举字符串数组

Asa*_*kov 7 arrays enums mongoose mongodb node.js

我有一个架构,其属性具有预定义的字符串数组类型。

这就是我尝试做的:

interests: {
    type: [String],
    enum: ['football', 'basketball', 'read'],
    required: true
}
Run Code Online (Sandbox Code Playgroud)

问题是,当我尝试向数组输入未在枚举上定义的错误值时,它不会使用枚举列表对其进行验证。

例如,这会通过,但它不应该通过:

{ "interests": ["football", "asdf"] }
Run Code Online (Sandbox Code Playgroud)

因为"asdf"枚举列表中没有预定义,所以它不应该通过验证,但不幸的是,它通过了验证并保存了它。

我尝试使用字符串类型的值而不是字符串数组来检查这个东西,并且它有效。

例如:

interests: {
    type: String,
    enum: ['football', 'basketball', 'read'],
    required: true
}
Run Code Online (Sandbox Code Playgroud)

例如,这按预期失败:

{ "interest": "asdf" }
Run Code Online (Sandbox Code Playgroud)

总之,我需要一个具有字符串数组类型的模式属性,该属性将根据预定义值检查其元素

实现这一目标最有效的方法是使用 validate 方法还是有更好的方法?

Idd*_*ohn 5

引用自这里

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

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