How to read a .env file on MongooseModule in Nestjs?

Viewed 862

So I am trying to add a config to my NestJs project, so far I've been using MongooseModule in order to connect to the Database but I was providing the full URL in MongooseModule.forRoot().

It was something like this:

//app.module.ts
import { Module } from '@nestjs/common';
import { MongooseModuele } from '@nestjs/mongoose';

@Module({
  imports: [MongooseModule.forRoot('mongodb://.....')]
})

So then I added the nestjs config and its looking like this:

//app.module.ts
import { Module } from '@nestjs/common';
import { MongooseModuele } from '@nestjs/mongoose';
import { ConfigModule, ConfigService } from '@nestjs/config';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
    }),
    MongooseModule.forRootAsync({
     imports: [ConfigModule],
     useFactory: async (config: ConfigService) => ({
      uri: config.get<string>('DB_HOST'),
     }),
     inject: [ConfigService],
   }),
  ]
})

But then got this error:

[Nest] 14098 - 06/01/2022, 7:16:42 AM ERROR [ExceptionHandler] Invalid scheme, expected connection string to start with "mongodb://" or "mongodb+srv://"

I also tried this way:

//app.module.ts
import { Module } from '@nestjs/common';
import { MongooseModuele } from '@nestjs/mongoose';
import { ConfigModule, ConfigService } from '@nestjs/config';

@Module({
  imports: [
    MongooseModule.forRootAsync({
     imports: [ConfigModule],
     useFactory: async (config: ConfigService) => ({
      uri: config.get<string>('DB_HOST'),
     }),
     inject: [ConfigService],
   }),
  ]
})

nest print this error:

ERROR [ExceptionHandler] The uri parameter to openUri() must be a string, got "undefined". Make sure the first parameter to mongoose.connect() or mongoose.createConnection() is a string.

My .env file looks like this:

DB_HOST="mongodb://....."

It seems like that on the app.module MongooseModule is not reading my .env file, does anyone knows how to solve that?

Thanks

2 Answers

Please try the following code, it works for me.

// app.module.ts
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config'
import { MongooseModule } from '@nestjs/mongoose';

@Module({
  import: [
    MongooseModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: async (config: ConfigService) => ({
        uri: config.get<string>('MONGODB_URI'), // Loaded from .ENV
      })
    })
  ],
})
export class AppModule {}

You do not need any configuration file. You can just write process.env.DATABASE_URL in app.module.ts file and set that env parameter from cmd like this:

set DATABASE_URL='url of your database'

and you can run your code

Related