在Nestjs中作为主体发送的对象中的验证键

问题描述 投票:0回答:1

我正在尝试将验证插入到PUT请求中(以更新存储在MongoDB中的某些数据):

DTO:

export enum reportFields {
    'startDate',
    'targetDateOfCompletion',
    'duration',
}


export class updateScheduleDto {
    @IsOptional()
    @IsString()
    readonly frequency?: string;

    @IsOptional()
    @IsArray()
    @IsEmail({}, { each: true })
    @IsString({ each: true })
    readonly emails?: string[];

    @IsOptional()
    @IsEnum(reportFields, { each: true })
    @IsArray()
    @IsString({ each: true })
    readonly reportFields?: string[];

    @IsOptional()
    @Type(() => Number)
    @IsNumber()
    updatedAt?: number;
}

Controller:

@Put('reports/:id/schedule')
async updateScheduleData(
    @Param('id') id: string,
    @Body(new ValidationPipe()) updateData: updateScheduleDto,
) {
    return this.reportService.updateScheduleData(id, updateData);
}

服务:

 async updateScheduleData(id: string, updateData: updateScheduleDto) {
        try {
            updateData.updatedAt = this.utils.getCurrentTime();
            const newData = await this.reportScheduleModel.findByIdAndUpdate(
                id,
                updateData,
                {
                    new: true,
                },
            );

            console.log(`Data has been updated to ${newData}`);
            return newData;
        } catch (error) {
            throw new Error('>>>' + error);
        }
    }

但是验证无法在密钥上进行。如果我在主体对象中传递了无效的密钥(如下所示),即使程序执行时没有任何错误,我该如何解决?我想念什么?

{
    "emaaaalls":["[email protected]"]
}
mongodb typescript validation nestjs dto
1个回答
0
投票
您需要将选项{ forbidUnknownValues: true }传递给ValidationPipe。当传入未知值时,这将使class-validator引发错误。You can read through the options here
© www.soinside.com 2019 - 2024. All rights reserved.