Mongoose - 无法访问createdAt

ffx*_*292 3 mongoose mongodb express typescript nestjs

我正在使用 Mongoose 创建一个 NestJs 应用程序,尽管我已将时间戳设置为 true,但目前尝试访问createdAt 时遇到问题,我的代码如下。

产品架构.ts

@Schema({timestamps: true})
export class Product extends Document {
  @Prop({ required: true })
  name!: string;
}
Run Code Online (Sandbox Code Playgroud)

产品.服务.ts

public async getProduct(name: string): Promise<void> {
    const existingProduct = await this.productModel.findOne({ name });

    if (!existingProduct) {
      throw new NotFoundException();
    }

    existingProduct.createdAt //Property 'createdAt' does not exist on type 'Product'
  }
Run Code Online (Sandbox Code Playgroud)

Jay*_*iel 9

仅仅因为您设置timestamps: true并不意味着打字稿理解这些字段应该存在。您需要将它们添加到类中,但没有@Prop()装饰器,以便打字稿知道字段存在,但 Nest 不会尝试为您重新创建字段。

  • 我的意思是你只需要将这两个属性添加到你的“Product”类中,而不需要使用“@Prop()”装饰器 (2认同)