Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

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

Hi I have the following code in NestJS.I am using moduleRef and have declared a custom provider named 'blogService'.However I am getting an error that says:

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

.What exactly am I doing wrong while declaring the custom provider which is leading to this error as it seems that I am injecting the Mongoose Model as well?

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

}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Not really sure why you're making a custom provider for this, other than possibly academic purposes. Either way, for anything you want to @InjectModel() or use getModelToken() for, you needx to have a MongooseModule.forFeature() call to register the custom provider the @nestjs/mongoose package will create for you. Once you have this you can use @InjectModel() or a custom provider like

{
  provide: 'blogService',
  inject: [getModelToken(Blog.name)],
  useFactory: (model: Model<Blog>) => new BlogService(model)
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda