【问题标题】:Nestjs - What is the correct way to create a DTO file to transform a nested json object?Nestjs - 创建 DTO 文件以转换嵌套 json 对象的正确方法是什么?
【发布时间】:2020-09-03 17:13:33
【问题描述】:

我正在尝试创建一个 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的值是undefined

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

【问题讨论】:

    标签: javascript node.js nestjs dto


    【解决方案1】:

    请通过这个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());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-22
      • 2018-12-05
      • 1970-01-01
      • 2011-06-07
      • 1970-01-01
      相关资源
      最近更新 更多