You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在NestJS中为数组结构编写DTO与Schema?

在NestJS中为含数组结构的学生数据编写DTO与Schema

我们先处理嵌套的subjects数组结构,不管是DTO还是数据库Schema,都需要先定义子结构,再在父结构中引用。


一、编写DTO(数据传输对象)

DTO用于验证和转换请求/响应数据,需依赖class-validator和class-transformer包(未安装则执行:npm install class-validator class-transformer)

1. 定义Subject子DTO

先编写数组内子对象的DTO:

// src/students/dto/subject.dto.ts
import { IsString } from 'class-validator';

export class SubjectDTO {
  @IsString()
  sNo: string;

  @IsString()
  name: string;

  @IsString()
  marks: string;

  @IsString()
  questionsAttempted: string;
}

2. 定义Student父DTO

在父级DTO中引用SubjectDTO,实现数组结构的验证:

// src/students/dto/student.dto.ts
import { IsNumber, IsString, ValidateNested, ArrayMinSize } from 'class-validator';
import { Type } from 'class-transformer';
import { SubjectDTO } from './subject.dto';

export class StudentDTO {
  @IsNumber()
  studentRollNo: number;

  @IsString()
  firstName: string;

  @IsString()
  class: string;

  @ValidateNested({ each: true }) // 验证数组中的每一个嵌套对象
  @ArrayMinSize(1) // 确保科目数组至少有一个元素
  @Type(() => SubjectDTO) // 指定嵌套对象的类型
  subjects: SubjectDTO[];
}

二、编写Mongoose Schema(用于MongoDB)

如果使用Mongoose操作MongoDB,需定义对应的Schema,依赖@nestjs/mongoose和mongoose包(未安装则执行:npm install @nestjs/mongoose mongoose)

1. 定义Subject子Schema

先编写子文档的Schema:

// src/students/schemas/subject.schema.ts
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';

export type SubjectDocument = Subject & Document;

@Schema()
export class Subject {
  @Prop({ required: true })
  sNo: string;

  @Prop({ required: true })
  name: string;

  @Prop({ required: true })
  marks: string;

  @Prop({ required: true })
  questionsAttempted: string;
}

export const SubjectSchema = SchemaFactory.createForClass(Subject);

2. 定义Student父Schema

在父级Schema中引用Subject Schema,声明数组类型的字段:

// src/students/schemas/student.schema.ts
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
import { Subject, SubjectSchema } from './subject.schema';

export type StudentDocument = Student & Document;

@Schema()
export class Student {
  @Prop({ required: true, unique: true })
  studentRollNo: number;

  @Prop({ required: true })
  firstName: string;

  @Prop({ required: true })
  class: string;

  @Prop({ type: [SubjectSchema], required: true }) // 指定为子文档数组
  subjects: Subject[];
}

export const StudentSchema = SchemaFactory.createForClass(Student);

内容的提问来源于stack exchange,提问作者Bhavani Dumpala

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 08:56:08