我有一个 Dto,如下所示:
import { Type } from "class-transformer";
import { ArrayMinSize, IsArray, ValidateNested} from "class-validator";
import { ObjectId } from "mongoose";
export class MongoIdDto {
@IsArray()
@ValidateNested({each: true})
@ArrayMinSize(1)
@Type(() => ObjectId)
ids: ObjectId[]
}
Run Code Online (Sandbox Code Playgroud)
但这给我带来了一个错误:
'ObjectId' only refers to a type, but is being used as a value here.
这个错误是怎么发生的呢?
我的控制器中有请求,这@Param是 MongoId 的字符串版本。如果我使用无效的字符串格式(不匹配 MongoId 格式)调用此请求,则该请求将继续执行,直到 MongoDB 调用抛出内部服务器错误。
我如何验证例如"aaa"“ANWPINREBAFSOFASD”未经过验证并在我的请求中尽早停止
当前控制器端点:
@Get(':id')
@ApiOperation({ summary: 'Get nice information' })
findOne(
@Param('id') id: string) {
return this.niceService.findOne(id);
}
Run Code Online (Sandbox Code Playgroud)
该服务称为:
async findOne(id: string): Promise<NiceDocument> {
const niceResult: NiceDocument = await this.NiceSchema.findById(id)
if (!niceResult) {
throw new NotFoundException()
}
return table
}
Run Code Online (Sandbox Code Playgroud)