Friday, August 19, 2022

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

Issue

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


Solution

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 {}


Answered By - Michael Morgan
Answer Checked By - Pedro (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.