首页 > 解决方案 > 如何在嵌套 js 中为 DTO 设置默认值?

问题描述

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

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

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

    @IsNotEmpty()
    length: number = 10;

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

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

如果未传递该值,则不应引发错误。

但是如果没有参数搜索,它应该会抛出一个错误。

标签: node.jsnestjsdto

解决方案


If you want to set a default value go to entity and set in the field for example in mongo db

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

推荐阅读