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

Required environment variables are absent in the application form

Currently, I am working on developing a Next.js application and implementing CRUD functionality. However, I encountered an error while creating the "Create" page, which seems to be related to environment detection. Just to provide some context, I am using ...

Sequelize Error: Object A is not linked to Object B in Node.js

Two models exist: Question and Answer. Each answer has a question_id, and a question can have multiple answers. I am trying to include all the answers for each question in my JSON response but keep encountering an error: "message": "answe ...

The code snippet 'onload='setInterval("function()",1000)' is not functioning as expected

I need to continuously load the contents of an XML file into a specific HTML div every second. Here is the JavaScript code that I am using to parse the XML file: function fetchEntries() { if (window.XMLHttpRequest) req = new XMLHttpRequest(); ...

Ensure there is a gap between each object when they are arranged in a

Is there a way to customize the layout of elements in the ratings view so that there is automatic spacing between them? I considered using text (white spaces) for this purpose, but it seems like an inefficient solution. Are there any other alternatives to ...

Violation of content security policy due to the usage of inline styling in the tawk.to

I have incorporated Tawk.to's chat widget codes into my website to include the chat bubble. The code is placed within a JS file: var Tawk_API = Tawk_API || {}, Tawk_LoadStart = new Date(); (function() { var s1 = document.createElement("script&qu ...

There is no 'Access-Control-Allow-Origin' header on the requested resource when connecting to a Heroku server

After deploying a Node.js + Express server to Heroku, I encountered an error while trying to use it: "Access to XMLHttpRequest at 'https://harel-shop-backend.herokuapp.com/auth/autologin' from origin 'http://localhost:3000' has ...

Exploring the power of Angular JS and Ionic by parsing data from a JSON

I'm currently developing an App with the IONIC framework and Angular JS, utilizing the Tinder cards feature recently introduced by Ionic (http://ionicframework.com/blog/tinder-for-x/). My goal is to read from a JSON file and use it as storage for my a ...

Exploring the assortment of reactions post-awaitReaction in node.js

The current code runs smoothly, but I encounter an issue when attempting to send messages after selecting either the X or check option. Instead of the expected outcome, I receive Despite my understanding that this collection is a map, all attempts to acce ...

Determining the return type of a function by analyzing its argument(s)

I'm interested in defining a method within a class that will have its type based on the argument provided in the constructor. For example: class A { private model: any; constructor(model: any) { this.model = model; } getModel( ...

Access environmental variables within Next.js middleware

Within my nextjs project, I have declared variables in both the .env and next.conf.js files. The code snippet from the next.conf.js file looks like this: module.exports = { env: { NEXT_PUBLIC_JWT_SECRET: "...", }, publicRuntimeConfig: { ...

Moving a field up one level in MongoDB using Node.js: A simple guide

I am faced with the task of transforming a large collection of documents, each in the following format: { _id: ... main: { case: ... csc: ... } } into this desired structure: { _id: ... case: ... csc: ... } While I came across ...

Is the Inline Partial<T> object still throwing errors about a missing field?

I recently updated to TypeScript version ~3.1.6 and defined an interface called Shop as follows: export interface Shop { readonly displayName: string; name: string; city: string; } In this interface, the property displayName is set by the backend a ...

Invoke Javascript through CSS selector

On my webpage, I have implemented a mousemove-mask feature that was inspired by an existing codepen. However, there is one significant issue that I can't seem to resolve on my own. Despite my attempts to fix it, I believe someone with more expertise c ...

Using v-model with the input type files in Vue.js allows for easy two

Is there a way to retrieve data from v-model array in an input type of "file" that allows multiple selections? <input type="file" multiple v-model="modFiles[index]"> <input type="file" multiple v-model="modFiles[index]"> <input type="file" ...

How can I modify an object within an array that is nested within an object, all stored within another array in a Mongoose database?

I have a document that looks like this, [ { "id": 1, "comments": [ { "mail": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b7c5d6ddf7d0dad6ded ...

Pass a byte array from the back-end code to an AJAX request

I have a web method where I am converting HTML to PDF and saving it to a local folder. The goal is for the user to download the file without needing to reload the page. To achieve this, I am attempting to make an AJAX POST call to the web method to retriev ...

Choosing Between Methods and Computed Properties in Vue.js

Can you explain the primary distinction between a method and a computed property in Vue.js? I'm finding it tricky to differentiate between the two as they appear quite similar. ...

Querying MongoDB for nested documents

My MongoDB data structure is as follows: { "_id" : ObjectId("512c4c468c08631ff0dbb02c"), "ReferenceNumber" : "MongoDb", "Title" : "Shashi", "CreatedUserId" : "users/1027", "Content" : "s", "CustomerId" : " ...

Tips for signaling to an AngularJS form that the input value has been altered

I developed a sign up form using angularjs. The submission process is functioning correctly. Now, I want to implement validation to check if the email provided is already registered. If it exists, display an error message indicating that the email is alrea ...

incorporating theme.spacing in the declaration of the theme

The theme setup that I am working with is as follows: export const themeDefault = createTheme({ themeName: 'Default (Mortgage Hub)', spacing: 4, ...typography, palette, components: { MuiButton: { styleOverrides: { root ...