nestjs

NestJS : TypeError: Cannot read property 'get' of undefined


I am trying to pass the connection parameters to mongodb by enviroment file and I am getting the following error

[Nest] 1176  - 12/10/2021 23:34:35   ERROR [ExceptionHandler] Cannot read property 'get' of undefined
TypeError: Cannot read property 'get' of undefined
    at MongoService.createMongooseOptions (/Users/Desarrollos/NestJS/nestjs-ventas-negocios/src/common/mongo/mongo.service.ts:20:41)
    at Function.<anonymous> (/Users/Desarrollos/NestJS/nestjs-ventas-negocios/node_modules/@nestjs/mongoose/dist/mongoose-core.module.js:135:120)
    at Generator.next (<anonymous>)
    at /Users/Desarrollos/NestJS/nestjs-ventas-negocios/node_modules/@nestjs/mongoose/dist/mongoose-core.module.js:20:71
    at new Promise (<anonymous>)
    at __awaiter (/Users/Desarrollos/NestJS/nestjs-ventas-negocios/node_modules/@nestjs/mongoose/dist/mongoose-core.module.js:16:12)
    at InstanceWrapper.useFactory [as metatype] (/Users/Desarrollos/NestJS/nestjs-ventas-negocios/node_modules/@nestjs/mongoose/dist/mongoose-core.module.js:135:45)
    at Injector.instantiateClass (/Users/Desarrollos/NestJS/nestjs-ventas-negocios/node_modules/@nestjs/core/injector/injector.js:294:55)
    at callback (/Users/Desarrollos/NestJS/nestjs-ventas-negocios/node_modules/@nestjs/core/injector/injector.js:43:41)
    at Injector.resolveConstructorParams (/Users/Desarrollos/NestJS/nestjs-ventas-negocios/node_modules/@nestjs/core/injector/injector.js:119:24)

This is the service mongo.service.ts

import { MongooseModuleOptions, MongooseOptionsFactory } from '@nestjs/mongoose';
import { Configuration } from '../../config/config.keys';
import { ConfigService } from '../../config/config.service';

export class MongoService implements MongooseOptionsFactory {
    constructor( private configService: ConfigService ) {}

    createMongooseOptions(): MongooseModuleOptions {

        const user     = this.configService.get(Configuration.DB_MONGO_USER);
        const password = this.configService.get(Configuration.DB_MONGO_PASSWORD);
        const server   = this.configService.get(Configuration.DB_MONGO_HOST);
        const database = this.configService.get(Configuration.DB_MONGO_DATABASE);

        return {
            uri: `mongodb://${user}:${password}@${server}/${database}?retryWrites=true&w=majority`,
        };
    }
}

And this I import it in the app.module.ts

@Module({
  imports: [
    MongooseModule.forRootAsync({
      useClass: MongoService,
    }),

Any suggestion, thanks, JM


Solution

  • You need 2 things here:

    1. Your MongoService needs to be marked with @Injectable() so that Nest can read the metadata of the constructor and set up the injection properly

    2. If your ConfigModule does not have a globally exported ConfigService, then in MongooseModule.forRootAsync() along with the useClass you need to have imports: [ConfigModule] so that you can inject the ConfigService