NestJs:如何注入具有 Mongoose 模型构造函数的 Provider?

NestJs: How can I inject a Provider that has a constructor with a Mongoose Model?

您好,我在 NestJS.I 中有以下代码,我正在使用 moduleRef 并声明了一个名为 'blogService' 的自定义提供程序。但是我收到一条错误消息:

'Nest can't resolve dependencies of the blogService (?). Please make sure that the argument BlogModel at index [0] is available in the AppModule context.'

。在声明导致此错误的自定义提供程序时,我到底做错了什么,因为我似乎也在注入 Mongoose 模型?

app.module.ts

import { BlogService } from './blog/service/blog.service';
import { Blog } from './blog/schema/blog.schema';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ConfigModule } from '@nestjs/config';
import { MongooseModule, getModelToken } from '@nestjs/mongoose';

        @Module({
          imports: [
            ConfigModule.forRoot({ isGlobal: true, load: [configuration], }),
            MongooseModule.forRoot(process.env.DATABASE_URL)
          ],
          controllers: [AppController],
          providers: [AppService, {
            provide: 'blogService',
            useFactory: () => BlogService,
            inject: [getModelToken(Blog.name)]
          }],
        
        })

app.controller.ts

import { Controller, Get } from '@nestjs/common';
import { ModuleRef } from '@nestjs/core';
import { BlogService } from './blog/service/blog.service';

@Controller()
export class AppController {
  constructor(private readonly modelRef: ModuleRef) { }

  @Get('blogs')
  async getAllBlogs(): Promise<any> {
    const response = await this.modelRef.get('blogService', { strict: false }).getAllBlogs();
    return response;
  }
}

blog.service.ts

import { Injectable, HttpException, HttpStatus, Logger } from '@nestjs/common';
import { Blog } from '../schema/blog.schema';
import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose';


@Injectable()
export class BlogService {

    private readonly logger = new Logger(BlogService.name);

    constructor(@InjectModel(Blog.name) private blogModel: Model<Blog>) { }


    async getAllBlogs() {
        try {
            const blogs = await this.blogModel.find().exec();
            return blogs;
        } catch (error) {
            this.logger.error(error.message);
        }
    }

}

不太确定您为什么要为此创建自定义提供程序,除了可能出于学术目的。无论哪种方式,对于任何您想 @InjectModel() 或使用 getModelToken() 的东西,您都需要调用 MongooseModule.forFeature() 来注册 @nestjs/mongoose 程序包将为您创建的自定义提供程序。一旦你有了这个,你就可以使用 @InjectModel() 或像

这样的自定义提供程序
{
  provide: 'blogService',
  inject: [getModelToken(Blog.name)],
  useFactory: (model: Model<Blog>) => new BlogService(model)
}