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.
Brian Koech
briankoech650@gmail.com

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:
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.