【问题标题】:Mongoose - can't access createdAtMongoose - 无法访问 createdAt
【发布时间】:2021-08-31 22:34:16
【问题描述】:

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

product.schema.ts

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

product.service.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'
  }

【问题讨论】:

    标签: typescript mongodb express mongoose nestjs


    【解决方案1】:

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

    【讨论】:

    • 那么你的意思是我应该在类中使用构造函数?
    • 我的意思是你只需要在没有@Prop() 装饰器的情况下将这两个属性添加到你的Product 类中
    猜你喜欢
    • 2021-08-20
    • 2021-02-06
    • 1970-01-01
    • 1970-01-01
    • 2017-03-23
    • 1970-01-01
    • 2016-07-22
    • 2016-12-18
    • 1970-01-01
    相关资源
    最近更新 更多