#Problem with ConfigModule on DatabaseModule

6 messages · Page 1 of 1 (latest)

young igloo
#

I had get a Error from Mongoose ERROR [MongooseModule] Unable to connect to the database. Retrying (1)... i have made a Module its named "common" in this is based a "database" module like as an (sub module). Now when i make it like my provided code snippet, process.env.DATABASE_URI dont work.

import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';

@Module({
  imports: [MongooseModule.forRoot(process.env.DATABASE_URI)],
})
export class DatabaseModule {}
``` ```ts
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { DatabaseModule } from './database/database.module';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
    }),
    DatabaseModule,
  ],
})
export class CommonModule {}
#

It only works like i provide my code snippet here. Can one here explain why? ```ts
@Module({
imports: [
MongooseModule.forRootAsync({
inject: [ConfigService],
useFactory: async (configService: ConfigService) => ({
uri: configService.get<string>('DATABASE_URI'),
}),
}),
],
})

cedar marsh
#

by the time that your code is reading process.env.DATABASE_URI, that env var was not read from dot env file yet

#

that's why you should always prefer using ConfigService instead of process.env

young igloo
#

Oh, okay Thanks! 🙂

cedar marsh
#

also because there's no validation over process.env.
only when ConfigModule has been properly initialized