javascript - MongoDB and class-validator unique validation - NESTJS - Stack Overflow

TL;DRI am trying to run mongoose query in my validatorHello, I am trying to make a custom decorator wh

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?

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?

Share Improve this question asked Oct 12, 2021 at 18:48 Nirjal PaudelNirjal Paudel 2016 silver badges12 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

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',
  })

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744089641a4556835.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信