NestJS使用Mongoose开启timestamps后无法访问createdAt属性问题
问题原因
你在@Schema装饰器中配置timestamps: true仅会让Mongoose运行时自动生成createdAt、updatedAt字段,TypeScript无法感知这两个字段的存在,因此触发了类型报错。
解决方案
方案1:直接在Schema类中显式声明字段
修改product.schema.ts,在Product类中补充两个时间字段的类型声明即可,不需要加@Prop装饰器:
@Schema({timestamps: true}) export class Product extends Document { @Prop({ required: true }) name!: string; // 新增时间戳字段类型声明 createdAt!: Date; updatedAt!: Date; }
方案2:封装通用基础类复用(多Schema场景推荐)
如果有多个Schema都开启了时间戳,可以提前定义通用基础类,避免重复编写声明:
// 单独定义base.document.ts export class BaseTimestampDocument extends Document { createdAt!: Date; updatedAt!: Date; } // product.schema.ts中继承即可 @Schema({timestamps: true}) export class Product extends BaseTimestampDocument { @Prop({ required: true }) name!: string; }
修改完成后重新编译项目,访问existingProduct.createdAt就不会再出现类型错误。
内容的提问来源于stack exchange,提问作者ffx292
相关产品推荐
相关产品推荐

