Blade
Blade

Reputation: 547

Nest.js only accept fields that are specified in a DTO

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;

Upvotes: 14

Views: 16354

Answers (1)

fazlu
fazlu

Reputation: 956

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

Upvotes: 32

Related Questions