Using TypeScript enum with mongoose schema

Viewed 9861

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?

2 Answers

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

const schema = new Schema ({
    enumProp: {
            type: Schema.Types.String,
            enum: enumKeys(EnumType),
            get: (enumValue: string) => EnumType[enumValue as keyof typeof EnumType],
            set: (enumValue: EnumType) => EnumType[enumValue],
        },
});

EDIT: Don't forget to explicitly enable the getter

schema.set('toJSON', { getters: true }); 
// and/or
schema.set('toObject', { getters: true });

This way you can fine-control how exactly you want to represent the prop in the db, backend and frontend (json response).

Related