外部布局上的嵌套/猫鼬访问数据库连接

时间:2020-07-01 17:23:54

标签: mongoose nestjs nest

我在custom-validator中使用猫鼬作为“ class-validator”时遇到问题; 通常,问题是访问数据库连接,connection.status始终为0,这意味着当我导入猫鼬并尝试访问模块外部的数据库时,我总是发现问题,请求是无限的:皱眉: 有代码供您考虑。谢谢

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

0 个答案:

没有答案