Swagger无法显示Mongoose Schema中的_id字段,求解决方案
解决Mongo文档_id属性在Swagger中不显示的问题
Mongoose的Document基类自带的_id属性不会被Swagger自动识别,需要在你的User类里显式声明并配置@ApiProperty装饰器,具体修改如下:
- 导入Mongoose的
Types类型用于类型提示 - 在
User类中添加_id字段的声明和Swagger装饰器配置
修改后的代码片段:
import { Document, Prop } from '@nestjs/mongoose'; import { ApiProperty } from '@nestjs/swagger'; import { Types } from 'mongoose'; // 其他必要导入... export class User extends Document { @ApiProperty({ description: '用户唯一标识ID', type: String // Swagger中显示为字符串格式更直观,实际运行时类型为Types.ObjectId }) _id: Types.ObjectId; // 原有的其他字段保持不变 @ApiProperty({ description: 'The username of the user' }) @Prop({ type: String, required: true }) username: string; // ...其余字段 }
如果项目中使用DTO(数据传输对象)定义API的请求/响应模型,同样需要在对应DTO类中添加_id字段的@ApiProperty配置,确保Swagger能正确识别该属性。
内容的提问来源于stack exchange,提问作者nerrood
相关产品推荐
相关产品推荐

