Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'
  }
like image 673
ffx292 Avatar asked Oct 23 '25 02:10

ffx292


1 Answers

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.

like image 112
Jay McDoniel Avatar answered Oct 25 '25 17:10

Jay McDoniel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!