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

如何在NestJS的Swagger中将ObjectId作为响应类型正确展示?

解决NestJS中Swagger识别MongoDB ObjectId类型的问题

当你在DTO中直接使用mongoose.Types.ObjectId作为字段类型时,Swagger会解析其内部结构(比如_bsontype等属性),从而将其展示为JSON对象而非预期的ObjectId字符串。可以通过以下两种方式修复:

方法一:在@ApiProperty中手动指定类型

直接在DTO的字段装饰器里明确类型为字符串,并标注格式为ObjectId,同时添加示例值:

import { ApiProperty } from '@nestjs/swagger';
import mongoose from 'mongoose';

export class CreateUserResponseDto {
  @ApiProperty({
    type: String,
    format: 'objectid',
    description: 'MongoDB 用户ID',
    example: '60d21b4667d0d8992e610c85'
  })
  userId: mongoose.Types.ObjectId;
}

这种方式适合单个DTO字段的快速调整,Swagger会直接将该字段展示为字符串类型(ObjectId格式),而非展开的JSON结构。

方法二:全局配置Swagger类型映射

如果你的项目中有大量ObjectId类型需要处理,可以在Swagger文档生成时全局替换类型,避免重复配置:

import { NestFactory } from '@nestjs/core';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { AppModule } from './app.module';
import mongoose from 'mongoose';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  const swaggerConfig = new DocumentBuilder()
    .setTitle('你的API')
    .setDescription('API文档')
    .setVersion('1.0')
    .build();

  // 全局处理ObjectId类型映射
  const swaggerDocument = SwaggerModule.createDocument(app, swaggerConfig, {
    schemaFactory: (schema) => {
      if (schema.properties) {
        Object.values(schema.properties).forEach((prop) => {
          // 识别ObjectId的内部结构并替换为字符串类型
          if (prop.type === 'object' && prop.properties?._bsontype) {
            prop.type = 'string';
            prop.format = 'objectid';
            delete prop.properties; // 移除原有的对象结构定义
          }
        });
      }
      return schema;
    },
  });

  SwaggerModule.setup('api', app, swaggerDocument);

  await app.listen(3000);
}
bootstrap();

全局配置后,所有DTO中的mongoose.Types.ObjectId字段都会被Swagger正确识别为字符串类型的ObjectId,无需逐个字段配置。


内容的提问来源于stack exchange,提问作者24sharon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 06:25:01