Transforming Data Store Objects to DTOs
Introduction
Welcome to this lesson on transforming data store objects to Data Transfer Objects (DTOs) in NestJS. So far, we've covered integrating MongoDB into your NestJS app, from installing and configuring MongoDB and Mongoose, to defining schemas for ToDo items and implementing the necessary service and controller layers for CRUD operations. In this lesson, we're going to focus on how to use DTOs with database objects, a crucial part of managing data flow efficiently in your application. We'll also introduce class-transformer, the library we'll use for transforming data, and explore how to implement these transformations in your NestJS application.
The Problem
Right now, our application is returning the data from the database exactly as Mongo gives it to us. That is a problem because the representation that Mongo stores data in is not always (often not, in fact!) the same representation that we want to expose from our API. For example, a Todo from our API currently looks like this:
That looks mostly correct except for the following issues:
- We don't want
_id. Instead, we wantid - What is
__v? That is an implementation detail of Mongo that we don't want to expose to the consumers of the API
We'd like the JSON to look more like this:
Overview of Data Transfer Objects (DTOs)
Data Transfer Objects (DTOs) are simple objects used to transfer data between different parts of an application. DTOs are especially useful in web applications for three main reasons:
- Validation: They ensure the data being transferred meets certain criteria.
- Transformation: They convert data from one format or structure to another.
- Encapsulation: They group related data together into a single object.
You used DTOs in the previous courses and we'll use them again. But how do we best return a DTO when whate we have is a Database Object?
Introduction to `class-transformer`
