Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose/NestJs can't access createdAt even though {timestamps: true}

I'm currently using Mongoose and NestJs and I'm struggling a bit regarding accessing the createdAt property.

This is my user.schema.ts

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

  @Prop({ required: true })
  email!: string;
}

export const UserSchema = SchemaFactory.createForClass(User);

and in my user.service.ts

public async getUser(
    id: string,
  ): Promise<User> {
    const user = await this.userModel.findOne({ id });

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

    console.log(user.createdAt) // Property 'createdAt' does not exist on type 'User' .ts(2339)
  }

So basically I've set timestamps to true but I'm still unable to access the createdAt property. By the way I also have a custom id which works fine so please ignore that in my service.ts

I've tried setting @Prop() createdAt?: Date to the schema but it still hasn't worked.

I've also tested this schema using MongoMemoryServer and Jest which shows that it returns createdAt.

Any help as to why I can't access the createdAt property would be greatly appreciated!

like image 543
ffx292 Avatar asked Jan 25 '26 15:01

ffx292


1 Answers

I have tested using this:

@Schema({ timestamps: true })

Then, I have added 2 fields in my model/entity (createdAt, updatedAt) to expose in the controller/resolver in NestJS.

@Prop()
  @Field(() => Date, { description: 'Created At' })
  createdAt?: Date

  @Prop()
  @Field(() => Date, { description: 'Updated At' })
  updatedAt?: Date

Final example:

import { ObjectType, Field } from '@nestjs/graphql'
import { Schema as MongooseSchema } from 'mongoose'
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'
@Schema({ timestamps: true })
@ObjectType()
export class Post {
  @Field(() => String)
  _id: MongooseSchema.Types.ObjectId
  @Prop()
  @Field(() => String, { description: 'Post Body ' })
  body: string

  @Prop()
  @Field(() => Date, { description: 'Created At' })
  createdAt?: Date

  @Prop()
  @Field(() => Date, { description: 'Updated At' })
  updatedAt?: Date
}

export const PostSchema = SchemaFactory.createForClass(Post)

Now, My new fields createdAt, updatedAt are available: enter image description here

like image 163
wilfredonoyola Avatar answered Jan 28 '26 04:01

wilfredonoyola



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!