Nestjs - What is the correct way to create a DTO file to transform a nested json object?

Viewed 4316

I am trying to create a DTO file to transform the values and save a Document.

export class CreateProductDto {
  readonly pricing: {
    readonly list: number;
  } 
}

async create(@Body() createProductDto: CreateProductDto) {
  console.log(createProductDto);
  console.log(createProductDto.pricing.list); 
}
import * as mongoose from 'mongoose';

export const ProductSchema = new mongoose.Schema({
  pricing: {
    list: {
      type: Number,
    },
  },
});

But the value of princing.list is undefined.

What is the correct way to do this in NestJS?

1 Answers

Please go through this documentation in your case your dto is going to be

import { IsNumber, IsObject } from 'class-validator';
import { Type } from 'class-transformer';
export class ListDto {
  @IsNumber()
  readonly list: number
}

export class CreateProductDto {
  @IsObject()
  @ValidateNested() @Type(() => ListDto)
  readonly pricing: ListDto
}

in your main.ts

import { ValidationPipe } from '@nestjs/common';
app.useGlobalPipes(new ValidationPipe());
Related