我正在使用 Nestjs 和 Mongoose orm 問題是 ValidationPipe 不會從請求中洗掉無效的道具并將給定的(原始)請求發送到我的服務。
這是main.ts
async function bootstrap() {
const app = await NestFactory.create(AppModule, {
cors: { origin: '*' },
});
app.useGlobalPipes(new ValidationPipe(
{
transform: true,
whitelist: true,
}
))
await app.listen(3002);
}
bootstrap();
這是update-category.dto
export class UpdateCategoryDto {
@IsDefined()
id:string
@IsDefined()
title: string;
@IsDefined()
url: string;
}
最后這是category.service
async updateCategories(categories: [UpdateCategoryDto]){
for (let i = 0; i < categories.length ; i ) {
console.log("given categories",categories);
await this.categoryModel.updateOne([{ _id: categories[i].id }],categories[i]);
}
}
這是我的簡單控制器
@Controller('categories')
export class CategoryController {
constructor(private categoryService: CategoryService) {}
@Put()
editCategories( @Body() updateCategories: [UpdateCategoryDto]) {
return this.categoryService.updateCategories(updateCategories);
}
}
當“給定類別”記錄專案時,它們具有前端發送到 api 的 _id,而我沒有在我的 dto 中將該道具列入白名單。為什么我會收到那個道具??我也試過‘forbidNonWhitelisted’,有趣的是請求沒有失敗:)) 似乎 useGlobalPipes 對我不起作用
uj5u.com熱心網友回復:
只需使用ParseArrayPipe.
更新您的controller.ts:
@Put()
editCategories(@Body(new ParseArrayPipe({ items: UpdateCategoryDto, whitelist: true })) updateCategories: [UpdateCategoryDto]) {
return this.categoryService.updateCategories(updateCategories);
}
確保擁有items并whitelist設定。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/387322.html
標籤:javascript 猫鼬 嵌套
上一篇:聚合時貓鼬更新檔案
