'How to create nested DTO class in NestJS corresponding to Schema

I am new to NestJs and trying to create nested schema in Mongoose as I want this data structure in my database:

{
  name:"John",
   age:28,
  address:{
     city:"Delhi",
     state:"Delhi
  }
} 

For this I have created below mongoose schema:

user.schema.ts

import mongoose from "mongoose";

export const UserSchema = new mongoose.Schema({

 name:{type:String},
 age:{type:Number},
 address:{
     city:{type:String},
     state:{type:String}
  }
});

How Can I write Dto class for this schema.Someone let me know As I want to add data inside database.



Solution 1:[1]

You can simply create two DTO classes in the following way.

export class AdressDto {
    readonly city: string;
    readonly state: string;
}
export class UserDto {
    readonly name: string;
    readonly age: number;
    readonly address: AdressDto
}

In the official Nestjs documentation you can find how to use DTO in your controllers, and you can also find how to use validators if you want to use them.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alex Dumitru