获取“查询模板时出错:TypeError:无法读取未定义的属性(读取“findOne”)”

问题描述 投票:0回答:1

我正在尝试在 Nest js 应用程序的自定义验证器类中使用我的 MongoDB 模型之一。我的模型是在名为“model”的文件夹中定义的。我正在使用 InjectModel 猫鼬在我的课堂上使用该模型。这种方法在我的服务文件中有效。但它在我的自定义验证文件中不起作用。 我的模式定义是这样的:

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { HydratedDocument } from 'mongoose';

export type TemplateDocument = HydratedDocument<Template>;

@Schema()
export class Template {
  @Prop({ required: true })
  name: string;

  @Prop({ required: true })
  content: string;

  @Prop({ required: true })
  path: string;

  @Prop({ required: false })
  isSelected: boolean;
}

export const TemplateSchema = SchemaFactory.createForClass(Template);

在我的模块文件中,我正在导入模板架构,如下所示:

import { Module } from '@nestjs/common';
import { TemplateController } from './template.controller';
import { TemplateService } from './template.service';
import { MongooseModule } from '@nestjs/mongoose';
import { Template, TemplateSchema } from 'src/models/template';

@Module({
  imports: [
    MongooseModule.forFeature([
      { name: Template.name, schema: TemplateSchema },
    ]),
  ],
  controllers: [TemplateController],
  providers: [TemplateService],
})
export class TemplateModule {}

我的自定义验证类位于同一文件夹“模板”中,但位于子目录中。 这是我的定制课程

import {
  registerDecorator,
  ValidationOptions,
  ValidatorConstraint,
  ValidatorConstraintInterface,
} from 'class-validator';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Template } from '../../../../models/template';
import { Injectable } from '@nestjs/common';

@ValidatorConstraint({ async: true })
@Injectable()
export class IsTemplateNotExist implements ValidatorConstraintInterface {
  constructor(
    @InjectModel(Template.name) private templateModel: Model<Template>,
  ) {}

  async validate(name: string): Promise<boolean> {
    try {
      console.log('this.templateModel = ', this.templateModel);
      const template = await this.templateModel.findOne({ name }).exec();
      console.log('template = ', template);
      return template === null; // Use null instead of undefined
    } catch (error) {
      console.error('Error while querying template:', error);
      return false; // Handle the error case appropriately
    }
    // return this.templateModel.findOne({ name }).then((template) => {
    //   console.log('tempate = ', template);
    //   return template === undefined;
    // });
  }
}

export function TemplateNotExist(validationOptions?: ValidationOptions) {
  return function (object: object, propertyName: string) {
    registerDecorator({
      target: object.constructor,
      propertyName: propertyName,
      options: validationOptions,
      constraints: [],
      validator: IsTemplateNotExist,
    });
  };
}

但是在验证方法上 this.templateModel 是未定义的 我不知道这个问题的原因。预先感谢您的帮助。我是 Nest js 和 mongodb 的新手。

node.js mongodb mongoose nestjs customvalidator
1个回答
0
投票

在发布我的问题之前,我从堆栈溢出显示的建议中得到了问题的解决方案。给我答案的问题实际上不是我提出的问题,而是看到我得到了答案。所以我想我应该将我的问题与答案一起发布,以便对其他人有所帮助..

实际上,在我的模块文件中,我忘记将

IsTemplateNotExist
类指定为提供者。我更新的模块文件如下所示:

import { Module } from '@nestjs/common';
import { TemplateController } from './template.controller';
import { TemplateService } from './template.service';
import { MongooseModule } from '@nestjs/mongoose';
import { Template, TemplateSchema } from 'src/models/template';
import { IsTemplateNotExist } from './validations/templateNotExist.rule';

@Module({
  imports: [
    MongooseModule.forFeature([
      { name: Template.name, schema: TemplateSchema },
    ]),
  ],
  controllers: [TemplateController],
  providers: [TemplateService, IsTemplateNotExist],
})
export class TemplateModule {}
© www.soinside.com 2019 - 2024. All rights reserved.