how-to-deploy-a-restful-api-using-nestjs-and-mongodb.html

How to Deploy a RESTful API Using NestJS and MongoDB

In today's digital landscape, building efficient and scalable web applications is paramount. One of the most effective ways to achieve this is by creating a RESTful API. NestJS, a progressive Node.js framework, makes it easy to design and deploy robust APIs, particularly when paired with MongoDB, a NoSQL database that excels in handling large volumes of data. This article will guide you through the process of deploying a RESTful API using NestJS and MongoDB, providing actionable insights and code examples along the way.

What is NestJS?

NestJS is a framework built on top of Node.js that embraces TypeScript, allowing developers to create efficient, reliable, and scalable server-side applications. Its architecture is heavily inspired by Angular, making it familiar to those who have experience with that framework. Key features of NestJS include:

  • Modular architecture: Facilitates organization and reusability of code.
  • Dependency injection: Promotes testability and maintainability.
  • Easy integration: Works seamlessly with various databases and libraries.

What is MongoDB?

MongoDB is a NoSQL database that stores data in JSON-like documents, making it flexible and easy to work with for developers. It allows for high scalability and performance, making it an excellent choice for applications that handle large amounts of data. Key benefits include:

  • Schema-less design: Allows for flexibility in data structures.
  • Horizontal scalability: Easily scales out by adding more servers.
  • Rich query capabilities: Supports complex queries and indexing.

Use Cases of RESTful APIs

RESTful APIs are essential in various scenarios, including:

  • Microservices architecture: Allowing different services to communicate.
  • Mobile applications: Serving as a backend for mobile apps.
  • Third-party integrations: Enabling other applications to interact with your service.

Prerequisites

Before diving into the coding part, ensure you have the following installed on your machine:

  • Node.js
  • npm (Node Package Manager)
  • MongoDB (local or cloud instance)
  • Nest CLI (npm install -g @nestjs/cli)

Step-by-Step Guide to Deploying a RESTful API

Step 1: Create a New NestJS Project

Start by creating a new NestJS project using the CLI:

nest new my-nest-api

This command will prompt you to choose a package manager. Select your preferred option (npm or yarn) and wait for the project to be set up.

Step 2: Install Required Packages

Navigate into your project directory:

cd my-nest-api

Install the necessary packages for MongoDB:

npm install @nestjs/mongoose mongoose

Step 3: Create a MongoDB Connection

Open the app.module.ts file and import the Mongoose module to establish a connection to your MongoDB database:

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/nest'), // Replace with your MongoDB connection string
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Step 4: Create a Model

Next, create a model that defines the structure of your data. In the src directory, create a new folder named cats and add a file named cat.schema.ts:

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';

@Schema()
export class Cat extends Document {
  @Prop({ required: true })
  name: string;

  @Prop()
  age: number;

  @Prop()
  breed: string;
}

export const CatSchema = SchemaFactory.createForClass(Cat);

Step 5: Create a Service and Controller

Now, create a service to handle the business logic. Create a new file named cats.service.ts in the cats folder:

import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Cat } from './cat.schema';

@Injectable()
export class CatsService {
  constructor(@InjectModel(Cat.name) private catModel: Model<Cat>) {}

  async create(cat: Cat): Promise<Cat> {
    const newCat = new this.catModel(cat);
    return newCat.save();
  }

  async findAll(): Promise<Cat[]> {
    return this.catModel.find().exec();
  }
}

Next, create a controller named cats.controller.ts:

import { Body, Controller, Get, Post } from '@nestjs/common';
import { CatsService } from './cats.service';
import { Cat } from './cat.schema';

@Controller('cats')
export class CatsController {
  constructor(private readonly catsService: CatsService) {}

  @Post()
  async create(@Body() cat: Cat) {
    return this.catsService.create(cat);
  }

  @Get()
  async findAll(): Promise<Cat[]> {
    return this.catsService.findAll();
  }
}

Step 6: Register the Module

Update the app.module.ts to include the new Cats module:

import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { CatsModule } from './cats/cats.module';

@Module({
  imports: [
    MongooseModule.forRoot('mongodb://localhost/nest'), 
    CatsModule,
  ],
})
export class AppModule {}

Step 7: Create a Cats Module

In the cats folder, create a new file named cats.module.ts:

import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { CatsController } from './cats.controller';
import { CatsService } from './cats.service';
import { Cat, CatSchema } from './cat.schema';

@Module({
  imports: [MongooseModule.forFeature([{ name: Cat.name, schema: CatSchema }])],
  controllers: [CatsController],
  providers: [CatsService],
})
export class CatsModule {}

Step 8: Run the Application

Finally, run your application:

npm run start

Your RESTful API should now be up and running! You can test it using tools like Postman or cURL.

Step 9: Testing Your API

To create a new cat, send a POST request to http://localhost:3000/cats with a JSON body:

{
  "name": "Fluffy",
  "age": 3,
  "breed": "Persian"
}

To retrieve all cats, send a GET request to http://localhost:3000/cats.

Troubleshooting Common Issues

  • MongoDB connection issues: Ensure your MongoDB instance is running and accessible.
  • Module not found: Check that all paths in your imports are correct.

Conclusion

Deploying a RESTful API using NestJS and MongoDB is a straightforward process that opens up many possibilities for modern web applications. With its modular architecture and powerful features, NestJS combined with MongoDB provides a robust solution for developers looking to build scalable APIs. By following the steps outlined in this article, you can create your own RESTful API and start integrating it into your applications today. Happy coding!

SR
Syed
Rizwan

About the Author

Syed Rizwan is a Machine Learning Engineer with 5 years of experience in AI, IoT, and Industrial Automation.