Home > Back-end >  How do I transform a MongoDB document into a NestJS DTO?
How do I transform a MongoDB document into a NestJS DTO?

Time:02-24

I have a data layer that reads and writes to a MongoDB instance. I only want to deal with MongoDB documents at that layer and not expose that implementation to my services.

Right now I am doing something like:

// users.repository.ts

...
async getUserById(id: string): Promise<UserDto> {
  const user = await this.model.findOne({ _id: id }).exec();
  return this.transformToDto(user);
}

private transformToDto(user: UserDocument): UserDto {
  return {
    id: user._id,
    ...etc
  }
}

...

This seems overly verbose and there must be a simpler way to achieve this without adding a helper to every repository.

Is there a cleaner way to achieve this?

CodePudding user response:

You can use class-transformer for that and you don't need to use extra helper methods it can be returned instantly.


import { plainToClass } from 'class-transformer';

class UserDto {
  id: string;
  email: string;
  role: string;
}

class Service {
  async getUserById(id: string): Promise<UserDto> {
    const user = await this.model.findOne({ _id: id }).exec();

    return plainToClass(UserDto, user);
  }
}

It will return transformed value which is UserDto

UserDto { id: 'U-111', email: 'U-111@email', role: 'user' }
  • Related