简体   繁体   中英

Using TypeScript enum with mongoose schema

I have a schema with an enum:

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);

The GameMap is an enum.

First problem is already in here: I need to convert the enum to a string array in order to use it with the schema.

Secondly, I wanna use an enum value directly during the schema creation.

new GameMap({
  name: 'Test',
  type: GameMode.ASSAULT
});

returns ValidationError: type: '1' is not a valid enum value for path 'type'.

I am not sure whether this can actually work due to the string array I set in the model enum property.

My idea would be to create some kind of type conversion during the schema creation. Does this work with mongoose or would I have to create some kind of helper for object creation?

GameMode.ASSAULT is evaluating as it's numeric value, but GameMode is expecting the type to be a string. What are you expecting the string evaluation to be? If you need the string value of the enum, you can access it with GameMode[GameMode.ASSAULT] , which would return ASSAULT as a string.

For example:

enum TEST {
    test1 = 1,
    test2 = 2
}

console.log(TEST[TEST.test1]);
//Prints "test1"

From the Mongoose docs on validation , in schema properties with a type of String that have enum validation, the enum that mongoose expects in an array of strings.

This means that CUtility.enumToArray(GameMode) needs to either return to you an array of the indexes as strings, or an array of the text/string values of the enum --whichever you are expecting to store in your DB.

The validation error seems to imply that 1 is not contained within the array that is being produced by CUtility.enumToArray(GameMode) , or the validation is seeing GameMode.ASSAULT as a number when it is expected a string representation of 1 . You might have to convert the enum value you are passing in into a string.

What is the output of CUtility.enumToArray(GameMode) ? That should help you determine which of the two is your problem.

Why don't you just create custom getter/setter:

customSchema.path('prop')
.get(function (enumValue: string) {
    return EnumType[enumValue as keyof typeof EnumType];
})
.set(function (enumValue: EnumType) {
    return EnumType[enumValue];
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM