Search code examples
javascripttypescriptmongodbmongoosenestjs

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!


Solution

  • 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