ffx292
ffx292

Reputation: 711

Mongoose - can't access createdAt

I'm creating a NestJs application using Mongoose, I'm currently having a problem trying to access createdAt even though I have set timestamps to true, my code is below.

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'
  }

Upvotes: 4

Views: 2196

Answers (1)

Jay McDoniel
Jay McDoniel

Reputation: 70490

Just because you set timestamps: true doesn't mean that typescript understands that those fields should exist. You need to add them to the class, but without the @Prop() decorator, so that typescript knows the fields exist, but Nest doesn't try to re-create the fields for you.

Upvotes: 12

Related Questions