首页 > 解决方案 > MongoDB 和类验证器唯一验证 - NESTJS

问题描述

TL;博士

我正在尝试在我的验证器中运行猫鼬查询


您好,我正在尝试制作一个自定义装饰器,如果该字段的值已经存在,则会引发错误。我正在尝试在验证路线的类中使用猫鼬模型。与解析器/控制器不同,@InjectModel()在验证器类中不起作用。我的验证器是这样的

import { getModelToken, InjectModel } from "@nestjs/mongoose";
import {
  ValidationArguments,
  ValidatorConstraint,
  ValidatorConstraintInterface,
} from "class-validator";
import { Model } from "mongoose";
import { User } from "../schema/user.schema";

@ValidatorConstraint({ name: "IsUniqueUser", async: true })
export class UniqueValidator implements ValidatorConstraintInterface {
  constructor(
    @InjectModel(User.name)
    private readonly userModel: Model<User>,
  ) {}

  async validate(value: any, args: ValidationArguments) {
    const filter = {};

    console.log(this.userModel);
    console.log(getModelToken(User.name));
    filter[args.property] = value;
    const count = await this.userModel.count(filter);
    return !count;
  }

  defaultMessage(args: ValidationArguments) {
    return "$(value) is already taken";
  }
}

而我使用上述装饰器的 DTO 是



@InputType({})
export class UserCreateDTO {
  @IsString()
  name: string;

  @IsUniqueUser({
    message: "Phone number is already taken",
  })
  @Field(() => String)
  phone: string;
}

控制台说 cannot read value count of undefined暗示这userModel是未定义的。

简而言之

我想在我的验证器中运行查询。我该怎么做?

标签: javascripttypescriptmongoosenestjsclass-validator

解决方案


根据这个问题(你不能注入依赖)

你应该添加你的main.ts

useContainer(app.select(AppModule), {fallbackOnErrors: true}); 

然后你需要像类一样将你的添加UniqueValidator到你的模块中@Injectable()

所以

...
providers: [UniqueValidator],  
...

然后,在您的 DTO 中,您可以添加:

@Validate(UniqueValidator, ['email'], {
    message: 'emailAlreadyExists',
  })

推荐阅读