How can I convert a MongoDB document into a DTO in NestJS?

I'm currently working with a data layer that interacts with a MongoDB database. My goal is to only handle MongoDB documents in this layer without exposing the implementation details to my services.

My current approach involves the following code:

// 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 method feels overly verbose and I believe there should be a more streamlined way to achieve the same result without having to include a helper function in every repository.

Is there a cleaner solution for this issue?

Answer №1

If you want to transform data easily without using extra helper methods, you can utilize class-transformer. This library allows for instant transformation.


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);
  }
}

The transformed value will be in the form of a UserDto object:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The function canvas.toDataURL() is not recognized - error originating from a node-webGL wrapper

I am currently working on converting client-side volume rendering code in the browser to server-side rendering using pure JavaScript. On the server side, I am utilizing node-webgl. My objective is to send the server's canvas content to the client so ...

Encasing the Angular 2 component template in a <div> tag

Currently, I have a parent component managing multiple child components. My goal is to enclose each child component's template with a *ngIf directive for conditional rendering. The number of children in the parent component can vary. Here is an examp ...

Exploring object properties within arrays and nested objects using ReactJS

Within the react component PokemonInfo, I am looking to extract the stats.base_stat value from the JSON obtained from https://pokeapi.co/api/v2/pokemon/1/. The issue lies in the fact that base_stat is nested inside an array called stats. My assumption is t ...

Support for BigInt is not available in TypeScript version 3.5.*

It seems that TypeScript has supported BigInt since version 3.2, and my project is using TypeScript 3.5. Despite not explicitly declaring any variables as BigInt, I recently integrated a package called BufferUtility from https://github.com/Pharuxtan/Buffer ...

Error TS2322: Type 'Partial<T>' is not assignable to type 'T'

I'm struggling to articulate my problem, so I think the best way to convey it is through a minimal example. Take a look below: type Result = { prop1: { val1: number, val2: string }, prop2: { val1: number } }; f ...

Adding the <a> tag causes Superfish to malfunction

I've been struggling to get the latest Superfish menu code working with lists that include the <a> tag. I've double-checked everything, but it seems like I'm missing something obvious. Can anyone help me figure out what's wrong? ...

The VueJs input file @change event only triggers once in Chrome after the first call

Here is the code snippet I am currently working with: HTML: <input id="task-message-input-upload" type="file" ref="file" @change="handleFileUpload($event)" /> Javascript : data() { return { uploadedFiles: [], show ...

Lambda function failing to execute Auth0 methods through the Auth0 node-auth0 SDK

I am working with a lambda function that triggers when a message is added to the SQS queue. Within the message, there is a userId that I want to connect to using the Auth0 node SDK. The code snippet for my GetUserDetails function below shows that it logs ...

Integrating external information with components

Currently in my React application, I am fetching a list of stores by directly calling the API through the URL. const getStore = async () => { try { const response = axios.get( 'http://localhost:3001/appointment-setup/storeList& ...

Conceal the results of echoing json_encode

One dilemma I encountered was passing an array from PHP to JavaScript using json_encode and ajax. The only method that seemed available was to use echo json_encode($var) This approach printed out the contents of $var on the page due to the echo statement ...

Ways to extract information from a text

I have a massive string, divided into two parts that follow this pattern: {\"Query\":\"blabla"\",\"Subject\":\"gagaga"}", {\"Query\":\"lalala"\",\"Subject\":\"rarara&bso ...

The click event triggered by the onclick clone/function may not always activate the click handler

As a newcomer in the JavaScript domain, I am encountering an issue where the first clone created after clicking 'add more' does not trigger my click me function. However, every subsequent clone works perfectly fine with it. What could be causing ...

Discovering the current time and start time of today in EST can be achieved by utilizing Moment.js

Need help with creating Start and End Time stamps using Moment.js in EST: Start Time should reflect the beginning of today End Time should show the current time. This is how I have implemented it using moment.js: var time = new Date(); var startTime=D ...

Leveraging Selenium to extract text from a dynamically populated DIV using JavaScript

I am currently utilizing Selenium to automatically retrieve all comments from a New York Times article. Once the comments are loaded, my goal is to extract them and save the information for future use. However, upon inspecting the source code of the articl ...

What steps are involved in creating a distinctive index within MongoDB?

Service that manages user accounts has a route for adding new accounts. It is imperative that the email field in each account is unique to avoid conflicts. To ensure uniqueness, an error should be thrown if a matching email is found. Currently, this check ...

Troubleshooting Azure typescript function: Entry point for function cannot be determined

project structure: <root-directory> ├── README.md ├── dist ├── bin ├── dependencies ├── host.json ├── local.settings.json ├── node_modules ├── package-lock.json ├── package.json ├── sealwork ...

jQuery's AJAX feature fails to identify the newly modified div classes

For my new website, I am developing a simple checklist feature. To handle the check and uncheck requests from users, I'm using jQuery's $.ajax() function. Whenever a user clicks on the check or uncheck buttons, jQuery retrieves the validation tok ...

Alternative form for non-javascript browsers in the absence of script

I'm currently working on a landing page for an upcoming product, and I've run into a bit of a snag. <form novalidate method="POST" class="subscribe-form"> <noscript> </form> <form method="POST" action="/ ...

Issue encountered while attempting to deactivate button until numerical data is entered in the OTP field using Vuejs

otp_value: '', isFadeout: false, verifyOtp() { this.disabled = true; this.otpBtnClicked = false; this.verified = true; }, <input class="o ...

What is the method for determining the type of a TypeScript class member that is associated with a commonly used symbol such as Symbol.toStringTag?

Does anyone know the correct TS syntax for extracting the type of a class method indexed with a well-known Symbol? Here are two incorrect methods: type T = String[Symbol.toStringTag]; // 'Symbol' only refers to a type, but is being used as a name ...