Home > Blockchain >  How do I rename mongoose connections in NestJs
How do I rename mongoose connections in NestJs

Time:09-27

I am having trouble giving a mongoose database connection a name (so that I can use more than one).

I have separated my database config out into a separate module so that I can import it easily when testing e2e.

My Database Module looks like:

import { Module } from "@nestjs/common";
import { MongooseModule } from "@nestjs/mongoose";
import { DatabaseService } from "./database.service";

@Module({
    imports: [
        MongooseModule.forRootAsync({
            //connectionName: 'database',
            useFactory: () => ({ uri: `mongodb://mongoUri` }),
        }),
    ],
    providers: [DatabaseService],
    exports: [DatabaseService]
})
export class DatabaseModule { };

and my Database Service is:

import { Injectable } from "@nestjs/common";
import { InjectConnection } from "@nestjs/mongoose";
import { Connection } from 'mongoose';

@Injectable()
export class DatabaseService {
    constructor(@InjectConnection() private readonly connection: Connection) {}

    getDbHandle(): Connection {
        return this.connection
    }
}

with App Module:

import { Module, NestModule } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { MyModule } from './my/my.module';
import { DatabaseModule } from './common/database/database.module';

@Module({
  imports: [
    MyModule,
    DatabaseModule
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule implements NestModule {}

and My Module:

import { Module } from '@nestjs/common';
import { MyService } from '../services/my.service';
import { MyController } from '../controllers/my.controller';
import { MongooseModule } from '@nestjs/mongoose';
import { My } from '../models/my.schema';

@Module({
  imports: [
    MongooseModule.forFeature([{ name: My.name, schema: MySchema }]) //, 'database'),
  ],
  controllers: [MyController],
  providers: [MyService]
})
export class MyModule {}

This all works fine, however if I uncomment the comments (i.e. add a connection name in Database Module and to the import in My Module, I get the error: Nest can't resolve dependencies of the DatabaseService (?). Please make sure that the argument DatabaseConnection at index [0] is available in the DatabaseModule context.

What is it that adding a connection name does to cause this error? And how can I resolve it? Any help greatly appreciated.

CodePudding user response:

Because @InjectConnection() takes an optional parameter which is the name, otherwise some "default" connection will be used.

See the source code here:

export const InjectConnection = (name?: string) =>
  Inject(getConnectionToken(name));

https://github.com/nestjs/mongoose/blob/master/lib/common/mongoose.decorators.ts

  • Related