如何让NestJS中Mongoose自动生成的timestamp纳入OpenAPI规范
解决NestJS Swagger未包含Mongoose自动生成的createdAt/updatedAt字段问题
方法一:在实体类中显式声明字段并添加Swagger装饰器
直接在Participant类里添加createdAt和updatedAt字段,通过@ApiProperty标记它们,Swagger就能识别并生成对应的OpenAPI规范:
@Schema({ timestamps: true }) export class Participant { @Prop() @ApiProperty() participantId: string; @Prop() @ApiProperty() name: string; @Prop() @ApiProperty() description: string; // 声明自动生成的时间字段,添加Swagger装饰器 @ApiProperty({ type: String, format: 'date-time', description: '记录创建时间' }) createdAt: Date; @ApiProperty({ type: String, format: 'date-time', description: '记录最后更新时间' }) updatedAt: Date; } export const ParticipantSchema = SchemaFactory.createForClass(Participant);
说明
- Mongoose的
timestamps: true配置会自动为文档填充createdAt和updatedAt值,无需手动赋值; - 添加
@ApiProperty后,NestJS Swagger插件会将这两个字段纳入OpenAPI Schema,生成对应的规范内容。
方法二:使用Swagger扩展装饰器(可选)
如果不想修改实体类,可以通过@ApiResponse的schema属性手动扩展返回结构,不过这种方式灵活性较低:
import { getSchemaPath } from '@nestjs/swagger'; @ApiOkResponse({ description: 'Get a participant', schema: { allOf: [ { $ref: getSchemaPath(Participant) }, { type: 'object', properties: { createdAt: { type: 'string', format: 'date-time' }, updatedAt: { type: 'string', format: 'date-time' } } } ] } }) @Get(':participantId') findOne( @Param('participantId') participantId: string, ): Promise<Participant> { return this.participantService.findOne(participantId); }
说明
- 使用
allOf将原有ParticipantSchema和新增的时间字段合并; - 需要从
@nestjs/swagger导入getSchemaPath工具函数。
验证效果
修改后重启项目,Swagger生成的OpenAPI规范中Participant Schema会包含createdAt和updatedAt字段,示例如下:
components: schemas: Participant: type: object properties: name: type: string description: type: string participantId: type: string createdAt: type: string format: date-time description: 记录创建时间 updatedAt: type: string format: date-time description: 记录最后更新时间 required: - name - description - participantId
内容的提问来源于stack exchange,提问作者Milindu Sanoj Kumarage
相关产品推荐
相关产品推荐

