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

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

我试图通过环境文件将连接参数传递给 mongodb,但出现以下错误

[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)

这是服务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`,
        };
    }
}

我将其导入 app.module.ts

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

任何建议, 谢谢, JM

这里需要两样东西:

  1. 你的 MongoService 需要用 @Injectable() 标记,以便 Nest 可以读取构造函数的元数据并正确设置注入

  2. 如果您的 ConfigModule 没有全局导出的 ConfigService,那么在 MongooseModule.forRootAsync() 中连同 useClass 您需要 imports: [ConfigModule] 这样你就可以注入 ConfigService

@Module({ 
  imports: [ 
    MongooseModule.forRootAsync({ 
      imports: [ ConfigModule ], 
      inject: [ConfigService],
      useClass: MongoService
  })
})