Hamed Mahdizadeh
Hamed Mahdizadeh

Reputation: 976

Nestjs with Mongodb native driver problem with injecting the connection

I've used Mongodb native node driver for my Nestjs project and when I run nest run command I faced this error:

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

Potential solutions:

  • If DATABASE_CONNECTION is a provider, is it part of the current AppModule?
  • If DATABASE_CONNECTION is exported from a separate @Module, is that module imported within AppModule? @Module({ imports: [ /* the Module containing DATABASE_CONNECTION */ ] })

The provider for DATABASE_CONNECTION has been defined in the database module and database module has been imported in the appModule and I can't find out the problem.

src/app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { ProjectController } from './project/project.controller';
import { ProjectService } from './project/project.service';
import { DatabaseModule } from './database.module';

@Module({
  imports: [DatabaseModule],
  controllers: [AppController, ProjectController],
  providers: [ProjectService],
})
export class AppModule {}

src/database.module.ts

import { Module } from '@nestjs/common';
import { MongoClient, Db } from 'mongodb';



@Module({
  providers: [{
      provide: 'DATABASE_CONNECTION',
      useFactory: async (): Promise<Db> => {
        try {
          const client = await MongoClient.connect('mongodb://127.0.0.1:27017', {
            useUnifiedTopology: true
          });
          return client.db('app-test');
        } catch(e){
          throw e;
        }
      }
    }
  ],
  exports:[
    'DATABASE_CONNECTION'
  ]
})
export class DatabaseModule { }

src/project/project.service.ts

    import { Inject, Injectable } from '@nestjs/common';
    import { Db } from 'mongodb';
    import { Project } from '../models/project.model';
    
    @Injectable()
    export class ProjectService {
        constructor(
            @Inject('DATABASE_CONNECTION')
            private db: Db
        ) {
    
        }
    
        async getProjects(): Promise<Project[]> {
            return this.db.collection('Projects').find().toArray();
        }
   }

Upvotes: 0

Views: 1417

Answers (1)

Hamed Mahdizadeh
Hamed Mahdizadeh

Reputation: 976

I finally fixed the error. I removed the content of dist folder and built the project again and start it and error fixed!

I think this could be helpful https://stackoverflow.com/a/66771530/3141993 for avoiding these type of errors without removing the content of dist file manually.

Upvotes: 0

Related Questions