Using TypeScript enum with mongoose schema
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:
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/orschema.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).