9

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 Answers2

15

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.

Dezzley
  • 1,463
  • 1
  • 13
  • 19
  • For those curious, this was implemented in Mongoose directly, rather than NestJS specifically. See this PR: https://github.com/Automattic/mongoose/pull/9547 – Jamie Syme May 25 '23 at 16:06
  • what should we do if we want to store roles instead of one role? – Sekomer Jun 08 '23 at 15:10
  • @Sekomer I suppose you should define it as the documentation recommends: `@Prop({ type: [{ type: String, enum: Role }] }) owner: Role[];` https://docs.nestjs.com/techniques/mongodb – Dezzley Jun 11 '23 at 11:50
  • 1
    thank you @Dezzley. I've found it after asking, unfortunately the syntax is pretty ugly :D – Sekomer Jun 11 '23 at 17:48
7

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
Exo
  • 237
  • 1
  • 2
  • 13