nestjs / mongoose

Mongoose module for Nest framework (node.js) 🍸
https://nestjs.com
MIT License
528 stars 118 forks source link

Creating Custom Class-validator method #466

Closed admicaa closed 4 years ago

admicaa commented 4 years ago

I'm Using nestjs in my new project, I found a problem when trying to make a new custom-validation rule, that using database, for example, if we have a role that validate whether the value is unique or not from mongodb, the request is infinite because I can't access the connection outside mongoose, so please can you help me figure this out

`import { registerDecorator, ValidationOptions, ValidationArguments, } from 'class-validator'; import * as mongoose from 'mongoose'; import { MongooseModule } from '@nestjs/mongoose'; import { mongooseConfig } from 'src/mongoseConfig';

export function Unique( property: string, column?: string, validationObject?: object, validationOptions?: ValidationOptions, ) { return function(object: Object, propertyName: string) { registerDecorator({ name: 'Unique', target: object.constructor, propertyName: propertyName, constraints: [property, column], options: validationOptions, validator: { defaultMessage(args: ValidationArguments) { return $property ($value) has been token before.; }, async validate(value: any, args: ValidationArguments) { let [ relatedPropertyName, columnName, validationObject, ] = args.constraints; let model = mongoose.model(relatedPropertyName); if (!columnName) { columnName = args.property; } if (!validationObject) { validationObject = {}; }

      validationObject[columnName] = value;
      let oldRecord = await model.findOne(validationObject).exec();
      if (oldRecord) {
        mongoose.disconnect();
        return false;
      } else {
        mongoose.disconnect();
        return true;
      }
    },
  },
});

}; } `

kamilmysliwiec commented 4 years ago

Please, use our Discord channel (support) for such questions. We are using GitHub to track bugs, feature requests, and potential improvements.