Home / Blogs / Building a RESTful API with NestJS and MongoDB
Tutorial

Building a RESTful API with NestJS and MongoDB

In this tutorial, we'll walk through the process of building a RESTful API using NestJS and MongoDB with Mongoose. You’ll learn how to set up the backend for a simple app, manage database connections, and implement basic CRUD (Create, Read, Update, Delete) operations with MongoDB.

BK

Brian Koech

briankoech650@gmail.com

Aug 30, 2025, 10:10:48 AM⏱️ 3 min read
Building a RESTful API with NestJS and MongoDB

Introduction

In this tutorial, we’ll create a RESTful API using NestJS and MongoDB. MongoDB is a NoSQL database that stores data in a flexible, JSON-like format. This is ideal for projects that need scalability, speed, and flexibility.

Prerequisites

Before we start, make sure you have the following installed:

  • Node.js

  • NPM or Yarn

  • MongoDB (or a cloud instance like MongoDB Atlas)

If you don’t have NestJS installed, run:

npm i -g @nestjs/cli

 

Step 1: Creating the NestJS Project

Let’s create a new NestJS project:

nest new nestjs-api

cd nestjs-api

 

Step 2: Installing Dependencies

Next, we’ll install the required dependencies for MongoDB and Mongoose:

npm install @nestjs/mongoose mongoose

 

Step 3: Setting up the Database

Open app.module.ts and configure the MongoDB connection:

import import { Module } from '@nestjs/common';

import { MongooseModule } from '@nestjs/mongoose';

import { AppController } from './app.controller';

import { AppService } from './app.service';

 

@Module({

  imports: [

    MongooseModule.forRoot('mongodb://localhost/nestjs-api', {

      useNewUrlParser: true,

      useUnifiedTopology: true,

    }),

  ],

  controllers: [AppController],

  providers: [AppService],

})

export class AppModule {}

 

This will connect to a MongoDB instance running locally. If you're using MongoDB Atlas, replace the URL with your Atlas connection string.

Step 4: Creating a Schema

In MongoDB, we define data structures with schemas. Let's define a User schema using Mongoose.

Create a user.schema.ts file:

import { Schema } from 'mongoose';

 

export const UserSchema = new Schema({

  name: { type: String, required: true },

  email: { type: String, required: true, unique: true },

});

 

Step 5: Creating the Users Module

Now, generate a new module for the users:

nest g module users

nest g service users

nest g controller users

 

In users.module.ts, import the UserSchema and register it with Mongoose:

import { Module } from '@nestjs/common';

import { MongooseModule } from '@nestjs/mongoose';

import { UserSchema } from './user.schema';

import { UsersService } from './users.service';

import { UsersController } from './users.controller';

 

@Module({

  imports: [MongooseModule.forFeature([{ name: 'User', schema: UserSchema }])],

  providers: [UsersService],

  controllers: [UsersController],

})

export class UsersModule {}

 

Step 6: Creating CRUD Operations

In the users.service.ts, define methods for CRUD operations. For example, a method to create a new user:

import { Injectable } from '@nestjs/common';

import { InjectModel } from '@nestjs/mongoose';

import { Model } from 'mongoose';

import { User } from './user.interface';

 

@Injectable()

export class UsersService {

  constructor(

    @InjectModel('User') private readonly userModel: Model<User>,

  ) {}

 

  async create(user: User): Promise<User> {

    const newUser = new this.userModel(user);

    return newUser.save();

  }

 

  // Other CRUD methods like findAll, findOne, update, delete can also be added here

}

 

Step 7: Creating Routes

Now, let’s set up the routes in users.controller.ts to handle requests:

import { Controller, Post, Body } from '@nestjs/common';

import { UsersService } from './users.service';

import { User } from './user.interface';

 

@Controller('users')

export class UsersController {

  constructor(private readonly usersService: UsersService) {}

 

  @Post()

  create(@Body() user: User): Promise<User> {

    return this.usersService.create(user);

  }

 

  // Additional routes for get, update, delete

}

 

Conclusion

In this tutorial, we’ve set up a basic NestJS API using MongoDB with Mongoose. This is just the beginning! You can now expand this project by adding more CRUD operations, validation, authentication, and much more.

 

Share this Blog

Related Articles

Ready to dive In?

Let's Build the Future, Together!

Whether you're a startup, enterprise, or government organization, we'll help you unlock new opportunities through technology.

  • Quality Quaranteed
  • Setup in Minutes
  • Best Engineers for the work

Newsletter

Stay ahead in tech and marketing—get insights, tips, and updates on software engineering, digital strategy, and business growth. Join our newsletter to fuel your success.

The information, content, and materials provided on this website are for general informational purposes only and may be subject to change without notice. While we strive for accuracy, BD Computing Limited makes no warranties or representations regarding the completeness, reliability, or suitability of the information and solutions presented.

Any unauthorized reproduction, distribution, or use of the content on this site is strictly prohibited. Logos, trademarks, and product names are the property of their respective owners. Use of this website constitutes acceptance of our Terms of Service and Privacy Policy.

© Copyright 2025 BD Computing LLC. All Rights Reserved.