11

I'm currently playing around with Nest.js and have a simple app with a route to register accounts. I created a DTO with a few fields as well as a mongodb schema. There is exactly one field in the mongodb schema I don't want to let a user modify on creation (=privilege), so I didn't specify that in the DTO.

However, if a user makes a request with the privilege property in the body, it'll still get saved to the DTO and then in the schema.

Is there a way to "cut off" any data from the body that doesn't match the DTO? I'm certain it did tell me once that there was a field it does not recognize, but it doesn't seem to work anymore. I tried to find a class validator or something, but couldn't find anything that fits and I don't really want to check every property myself...

Thanks in advance!


from account.service.ts

  async register(body: RegisterAccountDto) {
    return new_account.save();
  }

from 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);
  }

from account.schema.ts

  @Prop({ default: Privilege.USER })
  privilege: Privilege;
Blade
  • 477
  • 1
  • 7
  • 18

1 Answers1

23

For that purpose, you need to use the validation pipe of nestjs with whitelist property true.

Have a look at it: NestJs Validation

Goto main.ts

Add Import:

import { ValidationPipe } from '@nestjs/common';

then below line where app is being declared, add this line:

app.useGlobalPipes(new ValidationPipe({
    whitelist: true
  }));
fazlu
  • 856
  • 5
  • 10
  • Ah, the whitelist option did the trick! I had the validation pipe embedded, but without any configuration. Thanks a bunch! – Blade Jul 02 '20 at 19:08
  • 1
    @fazlu Is there any way we can do it only for a particular Module and not apply `whitelist` globally? – Chirag B Oct 03 '22 at 10:38
  • 1
    @ChiragB use this link to use the UsePipe decorator on a method level in the controller of a module, you will be able to use whitelist for a specific controller method of a specific module by following this: https://docs.nestjs.com/techniques/validation#transform-payload-objects – fazlu Oct 19 '22 at 21:00