In the @nestjs/mongoose module, to define enum types in a Mongoose schema, you need to use the enum keyword within the schema definition. An Enum restricts a field's value to a predefined set of options. Here is an example of defining and using Enum types in NestJS:
First, define an Enum type. For example, if you have a Role Enum representing user roles:
typescriptexport enum Role { ADMIN = 'admin', EDITOR = 'editor', USER = 'user' }
Next, use this Enum in the Mongoose schema definition. When defining the Schema, apply the @Prop decorator and pass an object to configure property options, including the Enum:
typescriptimport { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { Document } from 'mongoose'; import { Role } from './role.enum'; @Schema() export class User extends Document { @Prop({ required: true }) name: string; @Prop({ type: String, enum: Role, default: Role.USER }) role: Role; } export const UserSchema = SchemaFactory.createForClass(User);
In this example, we define a User class and its corresponding Mongoose schema. The role field is configured as an Enum type, restricting its value to one of the options defined in the Role Enum. We also provide a default value for the role field, set to Role.USER.
Using Enums ensures data consistency, as the database layer enforces that the role field's value must match one of the Enum's defined options. If you attempt to save a value outside this defined range, Mongoose will throw an error. This approach is highly beneficial for maintaining the integrity of your application's data.