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

Swagger无法显示Mongoose Schema中的_id字段,求解决方案

解决Mongo文档_id属性在Swagger中不显示的问题

Mongoose的Document基类自带的_id属性不会被Swagger自动识别,需要在你的User类里显式声明并配置@ApiProperty装饰器,具体修改如下:

  1. 导入Mongoose的Types类型用于类型提示
  2. 在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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 21:50:22