ffx292
ffx292

Reputation: 711

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!

Upvotes: 15

Views: 14521

Answers (2)

Mic Fung
Mic Fung

Reputation: 5692

I tested your code, adding @Prop() createdAt?: Date should be able to access createdAt.

The only thing I spot from your code where you cannot access createdAt is the id you pass to the query. The key should be _id

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

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

    console.log(user.createdAt)
}

Here is the screenshot of my testing using your code:

enter image description here

Upvotes: 9

wilfredonoyola
wilfredonoyola

Reputation: 515

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

Upvotes: 12

Related Questions