This article focuses on integrating mongoDB to a Nest Application.

Installation

Nodejs

You will need nodejs to run the application, if you don’t have already installed,you can install node.js from https://nodejs.org/en/download/

NestJS

Now install nest.js using command npm i -g @nestjs/cli

if you are using a MAC device and it throws npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules this error, run this script

$ sudo chown -R $(whoami) $(npm config get prefix)/{lib/node_modules,bin,share}

Adding mongodb to nestjs application

Now you can create a new project using nest new New-proj command

Now install the mongoose dependency using npm install @nestjs/mongoose mongoose command

Integration

Initialize connection in AppModule

Now in app.module.ts import mongoose module and give it the connection string to your database.

Now our mongoose connection to mongodb is done.

Create a schema

Schema the definition of data that we are going to store in database.

  • We Create different folders for diff domains.
  • Create a users folder inside src folder which will deal with users related logic.
  • Inside that create a schemas folder coz we can have more than 1 schemas.
  • In this eg we will only have one.
  • Create a file and lets call it user.schema.ts

This is a demo schema. Now we need to tell nestjs about the new schema we have created.

Module

Inside users module create a new file and lets call it users.module.ts

Repository

Now in order to use mongoose and to save or fetch data from database we will create a repository file namely users.repository.ts

Service

In order to test the new repository I have created the users.service to test things out.

Controller

After the service, we will also need a controller to expose an api, for this we will create users.controller.ts

Before you test the api make sure the application is running using yarn start:dev

Testing

To see this in action we can make post request to the backend using postman.

Screenshot 2021-12-22 at 10 13 20 PM

You can now view the database collection. I am using MongoDBCompass.

Screenshot 2021-12-22 at 10 13 20 PM

If you are not familiar with services I have uploaded this code to github

And now we have a fully working nestjs app with mongoDb.

If you liked this article, you can buy me a coffee

Categories:

Updated:

Nishant Gharat
WRITTEN BY

Nishant Gharat

Someone passionate about learning, and function effectively in a team. Someone who can develop a scalable working solution from an idea on a piece of paper. I like coding long rides and am a big foodie.

Leave a comment