乐闻世界logo
搜索文章和话题

How to set Enums in @nestjs /mongoose schema

1个答案

1

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:

typescript
export 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:

typescript
import { 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.

2024年6月29日 12:07 回复

你的答案