javascript - 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
是未定义的。
简而言之
我想在我的验证器中运行查询。我该怎么做?
解决方案
根据这个问题(你不能注入依赖)
你应该添加你的main.ts
useContainer(app.select(AppModule), {fallbackOnErrors: true});
然后你需要像类一样将你的添加UniqueValidator
到你的模块中@Injectable()
所以
...
providers: [UniqueValidator],
...
然后,在您的 DTO 中,您可以添加:
@Validate(UniqueValidator, ['email'], {
message: 'emailAlreadyExists',
})
推荐阅读
- visual-c++ - Visual C++ LNK2005 错误:已在 filename.obj 中定义变量名(使用 SFML)
- oracle - 合并oracle中的数据,没有重复的GRN行
- angular - Angular 7:Formvalidation,Validators.pattern 不起作用
- java - 如何访问偏好布局内的视图,Android
- daml - 从 Java 或 JavaScript 以外的语言使用 DAML Ledger API
- javascript - 拖拽上传
- swift - Swift 包构建错误:无法构建 Objective-C 模块“Darwin”
- case-insensitive - Blue Prism 决策阶段忽略字母大写
- reactjs - 在 xState 操作中设置上下文并触发方法
- ios - 如何在 Swift 4 中初始化代码生成的按钮边框