Nestjs - 创建 DTO 文件以转换嵌套 json 对象的正确方法是什么?

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

我正在尝试创建 DTO 文件来转换值并保存文档。

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,
    },
  },
});

但是princing.list的值是未定义

在 NestJS 中执行此操作的正确方法是什么?

请完成这个documentation 在您的情况下,您的 dto 将是

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
}

在你的 main.ts

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