Nest.js 只接受在 DTO 中指定的字段

Bla*_*ade 1 dto typescript class-validator nestjs

我目前正在使用 Nest.js 并有一个简单的应用程序,其中包含注册帐户的路径。我创建了一个包含几个字段和一个 mongodb 模式的 DTO。在 mongodb 模式中只有一个字段我不想让用户在创建时修改(=特权),所以我没有在 DTO 中指定它。

但是,如果用户使用正文中的权限属性发出请求,它仍将保存到 DTO,然后保存在架构中。

有没有办法“切断”身体中与 DTO 不匹配的任何数据?我敢肯定它曾经告诉我有一个它无法识别的领域,但它似乎不再起作用了。我试图找到一个类验证器或其他东西,但找不到任何合适的东西,我真的不想自己检查每个属性......

提前致谢!


来自 account.service.ts

  async register(body: RegisterAccountDto) {
    return new_account.save();
  }
Run Code Online (Sandbox Code Playgroud)

来自 account.controller.ts

  @ApiOperation({ summary: 'Register user', description: 'Register a new account' })
  @ApiConsumes('x-www-form-urlencoded')
  @ApiBody({ type: [RegisterAccountDto] })
  @Post('register')
  async register(@Body() body: RegisterAccountDto) {
    return this.accountService.register(body);
  }
Run Code Online (Sandbox Code Playgroud)

来自 account.schema.ts

  @Prop({ default: Privilege.USER })
  privilege: Privilege;
Run Code Online (Sandbox Code Playgroud)

faz*_*zlu 6

为此,您需要使用具有白名单属性 true 的 nestjs 验证管道。

看一看:NestJs 验证

转到 main.ts

添加导入:

import { ValidationPipe } from '@nestjs/common';
Run Code Online (Sandbox Code Playgroud)

然后在声明 app 的行下方,添加以下行:

app.useGlobalPipes(new ValidationPipe({
    whitelist: true
  }));
Run Code Online (Sandbox Code Playgroud)