[SOLVED] MongoDB and class-validator unique validation – NESTJS

Table of Contents



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 {
} from "class-validator";
import { Model } from "mongoose";
import { User } from "../schema/user.schema";

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

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

    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

export class UserCreateDTO {
  name: string;

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

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


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


providers: [UniqueValidator],  

Then, in your DTO you can add:

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

Answered By – monkeyUser

Answer Checked By – Cary Denson (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *