Search code examples
node.jstypescripttypegoose

Typegoose enum arrayProp returns an error: Type is not a constructor


I have got a problem with the definition of my array schema. So basically, what I wanted to achieve is a single user Model with a property called games, that holds an array of games user is playing. The problem is I have got defined games as enum:

module Constants {
    export enum Games {
        LOL = 'League Of Legends',
    }
}

export {Constants};

And now, when I try to attach it to the schema model like that:

@arrayProp({ required: true, items: Constants.Games })
games: Constants.Games[];

I receive an error (after a successful compilation, just before the server start)

^ const instance = new Type();
TypeError: Type is not a constructor
    at baseProp (C:\Users\Borys\Desktop\lft\backend\node_modules\typegoose\lib\prop.js:114:22)
    at C:\Users\Borys\Desktop\lft\backend\node_modules\typegoose\lib\prop.js:177:9
    at DecorateProperty (C:\Users\Borys\Desktop\lft\backend\node_modules\reflect-metadata\Reflect.js:553:33)
    at Object.decorate (C:\Users\Borys\Desktop\lft\backend\node_modules\reflect-metadata\Reflect.js:123:24)
    at __decorate (C:\Users\Borys\Desktop\lft\backend\build\dataModel\User.js:4:92)
    at Object.<anonymous> (C:\Users\Borys\Desktop\lft\backend\build\dataModel\User.js:64:1)

I have read a little bit about this error, but it relates to the required option for items/itemsRef I tried removing required, using enum, using even itemsRef and relating to the different set of documents but none of these worked for me.

Anyone could help/relate?


Solution

  • The problem is, you cannot use enums as an runtime mongoose type, so i would recommend using

    @prop({ required: true, type: String, enum: Constants.Games })
    games: Constants.Games[];
    
    • type for setting the type (which is string) (this option can be omitted - thanks to reflection)
    • enum for setting an enum to validate against