DEV Community

Perm Chao
Perm Chao

Posted on

NestJS connect to MongoDB

TL;DR

  • Create database provider by useFactor here
  • Create database module import database provider and export
  • Create your entity and make own provider by inject database provider here
  • import own provider to use in service

1) Create NestJS application with command line

nest new ${YOUR_APP_NAME}
cd ${YOUR_APP_NAME}
Enter fullscreen mode Exit fullscreen mode

2) Create database folder for collect database connector

mkdir database
Enter fullscreen mode Exit fullscreen mode

3) Make Database Provider by use useFactory

useFactory syntax allows for creating providers dynamically

You can connect multi database source

/* 
<project path>/src/database/database.provider.ts
*/

import * as mongoose from 'mongoose';

export const firstDatabaseProvider = {
 provide: '<Provider name>',
 useFactory: async (): Promise<mongoose.Connection> => {
  return await mongoose.createConnection('<MongoDB URI>')
 }
}

export const secondDatabaseProvider = {
 provide: '<Provider name>',
 useFactory: async (): Promise<mongoose.Connection> => {
  return await mongoose.createConnection('<MongoDB URI>')
 }
}
Enter fullscreen mode Exit fullscreen mode

4) Make Database module

/* 
<project path>/src/database/database.module.ts
*/

import * as mongoose from 'mongoose';
import { firstDatabaseProvider, secondDatabaseProvider } from './database.provider';

@Module({
  providers: [firstDatabaseProvider, secondDatabaseProvider],
  exports: [firstDatabaseProvider, secondDatabaseProvider],
})
export class DatabaseModules {}
Enter fullscreen mode Exit fullscreen mode

5) Run below command line to create CRUD application by nest-cli

nest g res ${YOUR_ENTITY}
cd ${YOUR_ENTITY}
Enter fullscreen mode Exit fullscreen mode

6) Create entity provider by go to file ${YOUR_ENTITY}.provider.ts

You can learn how to create model, mongoose schema and mongoose document in NestJS docs Here

import { Connection } from 'mongoose';
import { Entity ,EntitySchema } from './entities/yourEntity';

// use second database
import { secondDatabaseProvider } from '../database/database.provider'

export const myEntityProviders = [
  {
    provide: '<First Entity Provider Name>',
    useFactory: (connection: Connection) => connection.model(Entity.name, EntitySchema),
    inject: [financialDocDBProvider.provide],
  },
]

Enter fullscreen mode Exit fullscreen mode

7) make service

// ${YOUR_ENTITY}.service.ts

import { Inject, Injectable } from '@nestjs/common';
import { Model } from 'mongoose';
import { myEntityDocument } from './entities/entity.entity';
import { myEntityProviders } from './entity.provider';


@Injectable()
export class EntityService {
  constructor(@Inject(myEntityProviders[0].provide) private entityModel: Model<myEntityDocument>) {}

  async create(): Promise<myEntityDocument> {
    const newObj = new this.entityModel()

    return newObj.save();
  }

  findAll(): Promise<myEntityDocument[]> {
    return this.entityModel.find().exec();
  }
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)