在更新mongodb中的现有行时,如何在nestjs中阻止客户端中不需要的对象属性

问题描述 投票:1回答:2

创建新用户将忽略create-user.dto.ts中的非指定对象

但是,当我更新用户时,它会添加不需要的字段,如下所示:

// update-user.dto.ts
import { IsEmail } from 'class-validator';
import { Address } from '../model/address';

export class UpdateUserDto {
  firstName: string;

  lastName: string;

  @IsEmail(undefined, { message: 'Not a valid e-mail' })
  email: string;

  username: string;

  password: string;

  addresses: Address[];
}

这是来自用户服务的更新操作

// user.service.ts
  async update(data: UpdateUserDto) {
    try {
      this.logger.log(data);
      const id = '5c6dd9852d4f441638c2df86';
      const user = await this.userRepository.update(id, data);

      return { message: 'Updated your information' };
    } catch (error) {
      this.logger.log(error);
      throw new HttpException('', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

这是user.controller.ts

  @Patch()
  @UsePipes(CustomValidationPipe)
  async update(@Body() data: UpdateUserDto) {
    return this.userService.update(data);
  }

客户端补丁数据:

// Unwanted junk from client
{
  "email": "[email protected]",
  "junk": "junk"
}

email将正确更新,但该行将有一个新的不需要的属性junkjunk

node.js mongodb nestjs typeorm class-validator
2个回答
1
投票

我找到了解决方案:

这就是user.service.ts update()应该如下所示:

const user = await this.userRepository.create(data);

需要先添加

await this.userRepository.update(id, user);

这是完整的user.service.ts update()

  async update(data: UpdateUserDto) {
    this.logger.log(data);

    // added for testing purposes (id should be based on active user)
    const id = '5c6ef2c823bf4e3414d65cd0';
    const user = await this.userRepository.create(data);
    await this.userRepository.update(id, user);

    return { message: 'Updated your information' };
  }

现在,任何不需要的属性都不会添加到该行中


1
投票

我假设你在你的class-transformer中使用validateCustomValidationPipe方法。

当您将qazxsw poi选项传递给它时,qazxsw poi将删除所有未知( - > DTO类中没有注释)属性:

whitelist

如果您想抛出验证错误而不是仅仅剥离未知属性,您还可以传递validate选项。

validate(userUpdate, { whitelist: true })

在更新的情况下,您可能还想使用forbidNonWhitelisted,以便验证不会引发错误,例如validate(userUpdate, { whitelist: true, forbidNonWhitelisted: true }); 不是更新的一部分。


请注意,您应该在dto类中注释所有属性,以使验证正常工作:

skipMissingProperties: true
© www.soinside.com 2019 - 2024. All rights reserved.