简体   繁体   中英

MongoDB and class-validator unique validation - NESTJS

TL;DR

I am trying to run mongoose query in my validator


Hello, I am trying to make a custom decorator which throws an error if a value for that field already exists. I am trying to use the mongoose model inside the class that validates the route. Unlike in resolver/controller, @InjectModel() does not work in validator class. My validator is like this

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

and my DTO that uses the above decorator is



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

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

The console says cannot read value count of undefined implying that userModel is undefined.

InShort

I want to run the query in my validator. How can I do so?

According to this issue (you can't inject a dependency)

You should to add in your main.ts

import { useContainer } from 'class-validator';
useContainer(app.select(AppModule), {fallbackOnErrors: true}); 

Then you need to add your UniqueValidator to your module like an @Injectable() class

so

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

Then, in your DTO you can add:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM