Wednesday, 31 May 2017

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?



via Cludch

No comments:

Post a Comment