Search code examples
mongodbenumstypegoose

Modeling list of enums in typegoose


I have been trying to model an array of enums in typegoose like below, but keep having compile errors.

export enum USER_ROLES {
    ADMIN = 'admin',
    SUBSCRIBER = 'subs',
    NONE = 'none',
}


export class User {
    @prop({ type: () => [String], enum: USER_ROLES, default: [USER_ROLES.SUBSCRIBER] })
    roles?: USER_ROLES[];
}

export const UserModel = getModelForClass(User, {
    schemaOptions: {
        collection: 'users',
        timestamps: {
            createdAt: 'createdAt',
            updatedAt: 'createdAt',
        },
    }
});

The error message I get is:

Error: "User.roles"'s Type is invalid! Type is: "function String() { [native code] }" [E009]

Please how do I do it correctly?


Solution

  • I faced the similar problem earlier this morning, the right way to do this is as follows:

    export class User {
        @prop({ type: String, enum: USER_ROLES, default: [USER_ROLES.SUBSCRIBER] })
        roles?: USER_ROLES[];
    }
    

    type tells the type of objects the array will be holding. In this case it would String whose value could be one or more of admin, subs, or none.