how to set Enums in @nestjs/mongoose schema

Viewed 3123

this is my schema and i want to set the role to enum

@Prop({ required: true }) name: string;

@Prop({ required: true }) email: string;

@Prop({ required: true }) password: string;

@Prop() role: string;

this is how i used to do in mongoose

role: {
  type: String,
  enum: roles,
  default: 'user',
},

const roles = ['user', 'admin'];

2 Answers

you need to make an enum first:

enum Role {
  User, //or User = "user",
  Admin, // or Admin = "admin",
}

and then set it as the datatype

@Prop()
role: Role

The proper way to set enums is the following:

    @Prop({ type: String, enum: Role })
    role: Role

or:

    @Prop({ type: String, enum: Role, default: Role.User })
    role: Role

This way you achieve both Mongoose schema validation and TypeScript runtime data validation. If you omit the config inside the @Prop() decorator you could possibly insert any value into the role field by casting it to the Role enum:

    {
      role: 'blabla' as Role
    }

PS: In the previous versions of NestJs you must list the supported enums inside an array. See this issue.

Related