【问题标题】:How to set default values for DTO in nest js?如何在嵌套 js 中为 DTO 设置默认值?
【发布时间】:2020-09-29 01:29:39
【问题描述】:

我想为 DTO 中的节点设置默认值。因此,如果未传递该节点的值,则将使用默认值。虽然这是可行的,但我希望节点应该存在,值是可选的。

import { IsNotEmpty, IsDefined } from "class-validator";

export class IssueSearch
{
    @IsDefined()
    search: string;

    @IsNotEmpty()
    length: number = 10;

    @IsNotEmpty()
    lastId: string = "0"
}

这不符合我的目的。我希望像这样搜索 url http://base-url/folder?search=value

如果值没有被传递,它不应该抛出错误。

但如果参数搜索不存在,它应该会抛出错误。

【问题讨论】:

  • 您是否在 ValidationPipe 中使用transform: true 选项?
  • 是的...... @IsString() 装饰器成功了

标签: node.js nestjs dto


【解决方案1】:

如果要设置默认值,请转到实体并在字段中设置,例如在 mongo db 中

export class DumpDoc extends Document {
  @Prop()
  title: string;
  
  @Prop({ default: new Date() }) //set as default
  createdAt: string;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-24
    • 1970-01-01
    • 1970-01-01
    • 2019-04-08
    • 2022-01-25
    • 1970-01-01
    • 2021-06-07
    • 1970-01-01
    相关资源
    最近更新 更多