【发布时间】:2020-09-27 16:35:12
【问题描述】:
我正在尝试在 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;
}
控制器:
@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);
}
}
但验证无法通过密钥进行。如果我在 body 对象中传递了一个无效的键(如下所示),即使程序执行没有任何错误,我该如何解决这个问题?我错过了什么?
{
"emaaaalls":["randomemail123@gmail.com"]
}
【问题讨论】:
-
我遇到了完全相同的问题。我的配置与其他答案相同。我不知道为什么,但永远不会抛出错误 - 甚至在 findByIdAndUpdate 的 catch 事件中也没有。
标签: mongodb typescript validation nestjs dto