[英]Using TypeScript enum with mongoose schema
我有一个带有枚举的模式:
export interface IGameMapModel extends IGameMap, Document {}
export const gameMapSchema: Schema = new Schema({
name: { type: String, index: { unique: true }, required: true },
type: { type: String, enum: CUtility.enumToArray(GameMode) }
});
export const GameMap: Model<IGameMapModel> = model<IGameMapModel>('GameMap', gameMapSchema);
GameMap
是一个枚举。
这里已经存在第一个问题:我需要将枚举转换为字符串数组,以便将其与架构一起使用。
其次,我想在架构创建过程中直接使用枚举值。
new GameMap({
name: 'Test',
type: GameMode.ASSAULT
});
返回ValidationError: type: '1' is not a valid enum value for path 'type'.
由于我在模型枚举属性中设置的字符串数组,我不确定这是否可以实际使用。
我的想法是在模式创建期间创建某种类型转换。 这是否适用于猫鼬,还是我必须创建某种对象创建助手?
GameMode.ASSAULT
正在评估其数字值,但GameMode
期望类型为字符串。 您期望字符串评估是什么? 如果需要枚举的字符串值,则可以使用GameMode[GameMode.ASSAULT]
来访问它,它将以字符串形式返回ASSAULT
。
例如:
enum TEST {
test1 = 1,
test2 = 2
}
console.log(TEST[TEST.test1]);
//Prints "test1"
从Mongoose验证文档中 ,在具有enum
验证type
的String
type
的架构属性中, Mongoose期望的字符串数组中的enum
。
这意味着CUtility.enumToArray(GameMode)
需要返回给您一个作为字符串的索引数组,或者一个enum
的文本/字符串值数组(无论您希望存储在数据库中的那个数组)。
验证错误似乎暗示CUtility.enumToArray(GameMode)
生成的数组中不包含1
,或者当期望字符串表示形式1
时,验证将GameMode.ASSAULT
视为一个数字。 您可能必须将要传入的enum
值转换为字符串。
CUtility.enumToArray(GameMode)
的输出是什么? 那应该可以帮助您确定这两个是您的问题。
您为什么不创建自定义的getter / setter:
customSchema.path('prop')
.get(function (enumValue: string) {
return EnumType[enumValue as keyof typeof EnumType];
})
.set(function (enumValue: EnumType) {
return EnumType[enumValue];
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.