简体   繁体   English

如何将 MongoDB 文档转换为 NestJS DTO?

[英]How do I transform a MongoDB document into a NestJS DTO?

I have a data layer that reads and writes to a MongoDB instance.我有一个读取和写入 MongoDB 实例的数据层。 I only want to deal with MongoDB documents at that layer and not expose that implementation to my services.我只想在该层处理 MongoDB 个文档,而不将该实现公开给我的服务。

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?有没有更清洁的方法来实现这一目标?

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM