NestJS中Swagger嵌套数据结构请求体展示异常求助
NestJS Swagger 嵌套数组DTO 文档展示修复方案
问题场景
使用NestJS开发API并通过Swagger生成接口文档时,CreateWoopDto中的content字段(类型为WoopStatementDto[])在Swagger文档的请求体中未正确展示嵌套数组结构,无法体现数组内元素的字段定义。
原DTO代码如下:
export class CreateWoopDto { @ApiProperty() @IsUUID() user_id: string; @ApiProperty() @ValidateNested({ each: true }) @Type(() => WoopStatementDto) @IsArray() content: WoopStatementDto[]; } export class WoopStatementDto { @ApiProperty() @IsString() if: string; @ApiProperty() @IsString() then: string; }
解决方案
问题根源在于@ApiProperty()未明确指定数组的嵌套元素类型,Swagger无法自动推断完整结构。只需修改content字段的@ApiProperty装饰器配置,明确声明数组类型及元素DTO:
export class CreateWoopDto { @ApiProperty() @IsUUID() user_id: string; // 修改此处的@ApiProperty配置 @ApiProperty({ type: [WoopStatementDto] }) @ValidateNested({ each: true }) @Type(() => WoopStatementDto) @IsArray() content: WoopStatementDto[]; } export class WoopStatementDto { @ApiProperty() @IsString() if: string; @ApiProperty() @IsString() then: string; }
原理说明
通过@ApiProperty({ type: [WoopStatementDto] }),我们明确告诉Swagger:
content是一个数组(通过数组包裹类型的写法[WoopStatementDto])- 数组中的每个元素都遵循
WoopStatementDto的字段定义
修改后,Swagger文档会正确展示content为数组结构,每个元素包含if和then两个字符串字段。
内容的提问来源于stack exchange,提问作者Ping Zhao
相关产品推荐
相关产品推荐

