Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

201
Visualizações
How do I transform a MongoDB document into a NestJS DTO?

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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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' }
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda