16

I am a beginner in NestJS and I want to write a DTO for below structure -

{
    something: {
        info: {
            title: string,
            score: number,
            description: string,
            time: string,
            DateOfCreation: string
        },
        Store: {
            item: {
                question: string,
                options: {
                    item: {
                        answer: string,
                        description: string,
                        id: string,
                        key: string,
                        option: string
                    }
                }
            }
        }
    }
}

I want to write a DTO for that nested Data object. I can't find a solid example for writing nested DTO in NestJS. I am a beginner in NestJS and I have never worked with DTO before. So please don't assume that I know something. I am using it with Mongoose.

user3399180
  • 476
  • 2
  • 7
  • 18

2 Answers2

34

You will have to create separate classes for each object in your schema and a main class which will import all the classes.

import { Type } from "class-transformer";

class Info {
    readonly title:string
    readonly score:number
    readonly description:string
    readonly dateOfCreation:Date
}

export class SampleDto {
    @Type(() => Info)
    @ValidateNested()
    readonly info: Info

    ...Follow same for the rest of the schema

}

Refer: https://github.com/typestack/class-validator#validating-nested-objects

Istiyak Tailor
  • 1,570
  • 3
  • 14
  • 29
  • 2
    Ooh my god this thing was staring right at my face but I couldn't see it. Thank you very much. Marking this as accepted answer. And here's another answer for same question for future readers - https://stackoverflow.com/questions/53786383/validate-nested-objects-using-class-validator-and-nestjs – user3399180 Jun 05 '21 at 15:37
  • 2
    Note that it's @ValidateNested(), not @ValidatedNested() – kmeshavkin Dec 01 '21 at 14:42
  • From where to import @Type. I can not find it in class-validator – Ibad Shaikh Dec 06 '22 at 12:23
  • 1
    import { Type } from "class-transformer"; – Ibad Shaikh Dec 06 '22 at 13:43
-3

//example :

export class UserBaseDto {
  @ApiProperty({
    type: String,
    required: true,
    description: 'email user, minlength(4), maxlength(40)',
    default: "test@email.com",
  })
  @IsString()
  @MinLength(4)
  @MaxLength(40)
  @IsNotEmpty() 
  email: string;
//....enter code here
}
Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39