title: How to create a mongodb connection provider in Nestjs
body: <p>I am trying to create a database connection provider in Nestjs for MongoDB.</p>
  
  <p>I inspected the <code>user.controller.ts</code> and mongoDbProvider by putting breakpoints and found that the controller gets before the database connection is made. How do I make a database connection before the controllers get initialized?</p>
  
  <p>Nest.js documentation says that useFactory method will run before any other module that depends on it.</p>
  
  <blockquote>
    <p><code>src/mongo-db/mongodb.provider.ts</code></p>
  </blockquote>
  
  <pre><code>import { MongoClient } from "mongodb";
  import { MONGODB_PROVIDER } from "../constants";
  
  export const mongoDbProviders = [
    {
      provide: MONGODB_PROVIDER,
      useFactory: async () =&gt; {
        MongoClient.connect('mongodb://localhost:27017',
          { useUnifiedTopology: true },
          (error, client) =&gt; {
            return client.db('nestjs-sample');
          });
      }
    },
  
  ];
  </code></pre>
  
  <blockquote>
    <p><code>src/mongo-db/mongo-db.module.ts</code></p>
  </blockquote>
  
  <pre><code>import { mongoDbProviders } from './mongo-db.providers';
  
  @Module({
    providers: [...mongoDbProviders],
    exports: [...mongoDbProviders],
  })
  export class MongoDbModule {
  
  }
  </code></pre>
  
  <blockquote>
    <p><code>src/constants.ts</code></p>
  </blockquote>
  
  <pre><code>export const MONGODB_PROVIDER = 'MONGODB_CONNECTION';
  </code></pre>
  
  <p>I imported <code>MongoDbModule</code> into <code>user.module.ts</code></p>
  
  <blockquote>
    <p><code>src/user/user.module.ts</code></p>
  </blockquote>
  
  <pre><code>import { Module } from '@nestjs/common';
  import { UserController } from './user.controller';
  import { UserService } from './user.service';
  import { MongoDbModule } from 'src/mongo-db/mongo-db.module';
  
  @Module({
    imports: [MongoDbModule],
    controllers: [UserController],
    providers: [UserService]
  })
  export class UserModule {}
  </code></pre>
  
  <p>Here I injected the <code>db</code> from <code>mongoDbProvider</code> into <code>UserController</code> constructor. But the constructor runs before db connection.</p>
  
  <blockquote>
    <p><code>src/user/user.controller.ts</code></p>
  </blockquote>
  
  <pre><code>import { Controller, Post, Req, Get, Res, Inject } from '@nestjs/common';
  import { Request, Response } from "express";
  import { MONGODB_PROVIDER } from 'src/constants';
  
  @Controller('users')
  export class UserController {
  
    constructor(@Inject(MONGODB_PROVIDER) private readonly db: any) {
  
    }
  
    @Post()
    async create(@Req() request: Request, @Res() response: Response) {
      this.db.collection('users').insertOne(request.body, (err, result) =&gt; {
        if (err) {
          response.status(500).json(err);
        } else {
          response.status(201);
          response.send(result);
        }
      });
    }
  
    @Get()
    get(@Req() request: Request, @Res() response: Response) {
      response.status(400).json({
        message: 'kidilam service'
      });
    }
  
  }
  </code></pre>