how to set Enums in @nestjs/mongoose schema

11.7k Views Asked by At

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'];
3

There are 3 best solutions below

0
On

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
4
On

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.

0
On

This is how you can assign:

src\constants\api.enums.ts

export enum ROLES {
 USER,
 ADMIN,
 SUPER_ADMIN,
}

src\schemas\user.schema.ts

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { ROLES } from '../constants/api.enums';
import { IsEnum } from 'class-validator';
    
@Schema()
export class User {
 @Prop({ type: String, enum: ROLES, default: ROLES.USER })
 @IsEnum(ROLES)
 roles: string;
}
export const UserSchema = SchemaFactory.createForClass(User);