how to set Enums in @nestjs/mongoose schema
Asked Answered
P

3

12

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'];
Phenocryst answered 17/6, 2021 at 6:25 Comment(0)
O
23

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.

Olly answered 29/6, 2022 at 16:15 Comment(4)
For those curious, this was implemented in Mongoose directly, rather than NestJS specifically. See this PR: github.com/Automattic/mongoose/pull/9547Greenbelt
what should we do if we want to store roles instead of one role?Caswell
@Sekomer I suppose you should define it as the documentation recommends: @Prop({ type: [{ type: String, enum: Role }] }) owner: Role[]; docs.nestjs.com/techniques/mongodbOlly
thank you @Dezzley. I've found it after asking, unfortunately the syntax is pretty ugly :DCaswell
S
9

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
Stelu answered 17/6, 2021 at 10:25 Comment(0)
D
0

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);
Delmore answered 13/9, 2023 at 13:16 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.