mariachiacero.com

Setting Up a Nest.js Server with MongoDB for 2024: A Guide

Written on

Chapter 1: Introduction to Nest.js

In 2024, the process of establishing a Nest.js server with MongoDB for a registration form project is streamlined and efficient. Initially, I attempted to build the back-end using Next.js, only to discover that its complexity was unnecessary for the smaller project I was working on. This led me to consider simpler alternatives, and Nest.js emerged as the perfect solution due to its user-friendly nature.

Setting up a Nest.js server with MongoDB

Chapter 2: Why Choose Nest.js Over Other Frameworks?

This section serves as a continuation from my previous article, where I explored the front-end aspect: “How to Implement Firebase User Authentication with React.js.” While using Next.js, I encountered several challenges. Although it is primarily tailored for React applications and is robust with numerous features, its focus on client-side rendering and static site generation can be overly complicated for smaller projects that require a straightforward back-end solution.

Opting for Node.js also posed challenges. It's clear that backend applications in Node.js often lack a structured framework, which can lead to a considerable time investment in system architecture. Fortunately, Nest.js simplifies this process, allowing for more efficient development.

Key Components in Nest.js

  • Module: The app.module.ts file serves as the entry point for any Nest.js application.
  • Controller: This component manages incoming requests and generates appropriate responses via application APIs.
  • Service: The service file manages the database connection and CRUD (Create, Read, Update, Delete) operations.
  • Model: In Nest.js, a model acts as a representation of a real-world entity, corresponding to a database table.

Chapter 3: Initial Setup of Nest.js

Step 1: Installing Nest CLI and Project Initialization

For detailed initial steps, refer to the official documentation. Here’s a brief overview of the commands involved:

npm install -g @nestjs/cli # Install the Nest CLI globally

nest new server-name # Create a new Nest.js project

cd server-name # Navigate to the project directory

npm run start:dev # Start the development server

Executing these commands will launch the development server, and you'll see output confirming that your Nest.js application is operational. Access your app in a web browser.

Nest.js "Hello World!" Page

You can verify that your server is running by visiting http://localhost:3000.

Note:

Always consult the official Nest.js documentation and GitHub repository for updates or changes specific to the 2024 version. The steps mentioned here are based on standard practices as of my last knowledge update.

Step 2: Setting Up MongoDB

The foundational steps for integrating MongoDB can be found in the official MongoDB documentation, so I will skip over those details.

npm i @nestjs/mongoose mongoose

Import the Mongoose module into your main src/app.module.ts file as follows:

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

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

@Module({

imports: [MongooseModule.forRoot('mongodb://localhost/nest')],

})

export class AppModule {}

Chapter 4: User Module Creation

Step 3: Establishing the User Module in /src/service/user.service.ts

To manage user functionalities, let's create a dedicated user module within your Nest.js application. This module will include the user controller, service, and schema.

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

import { User, UserDocument } from './user.models';

import { Model } from 'mongoose';

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

import { v4 as uuidv4 } from 'uuid';

@Injectable()

export class AppService {

constructor(@InjectModel('user') private readonly userModel: Model<UserDocument>) {}

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

const newUser = new this.userModel(user);

newUser.id = uuidv4();

return newUser.save();

}

async findAll() {

return await this.userModel.find().exec();

}

}

Step 4: Integrating UserModule into AppModule

Next, update the src/app.module.ts file to include the UserModule:

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

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

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

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

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

@Module({

imports: [

MongooseModule.forRoot('MONGO_DB_DATA'),

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

],

controllers: [AppController],

providers: [AppService],

})

export class AppModule {}

Step 5: Adding User Endpoints in AppController

Now, let's implement user-related endpoints in the AppController for your Nest.js application, which will include actions for creating a new user and retrieving all users.

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

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

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

@Controller()

export class AppController {

constructor(private readonly appService: AppService) {}

@Post('users')

async createUser(@Body() SendUserDto: User) {

return await this.appService.createUser(SendUserDto);

}

@Get('users/all')

async findAll(@Query() { skip, limit }): Promise<User[]> {

return this.appService.findAll();

}

}

Step 6: Defining the User Schema

The following code snippet defines a User schema using the @nestjs/mongoose module in Nest.js, representing the structure of user data to be stored in a MongoDB database.

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

import { Document } from "mongoose";

export type UserDocument = User & Document;

@Schema()

export class User {

@Prop() uid: string;

@Prop() email: string;

@Prop() password: string;

@Prop() birthday: string;

@Prop() surname: string;

@Prop() name: string;

@Prop() familyname: string;

@Prop() passport: string;

@Prop() gender: string;

@Prop() phone: string;

@Prop() country: string;

@Prop() region: string;

@Prop() city: string;

@Prop() address: string;

@Prop() postindex: string;

}

export const UserSchema = SchemaFactory.createForClass(User;

You can now utilize PostMan to execute your first API call.

PostMan interface showing API results

Chapter 5: Summary

In summary, as I embarked on my freelance project centered around a registration form, the choice of technology for the backend was vital. Nest.js emerged as the optimal solution, offering a more streamlined and simplified approach compared to the complexities of Next.js. This decision was motivated by the need for simplicity in a smaller project that required a straightforward backend. To validate the server's functionality, I used PostMan and successfully retrieved user data, confirming that everything is functioning as intended.

Thank you for visiting!

Feel free to check out my other articles:

  • What I’ve Learned From My First Year on Medium, And How I Plan To Continue Growing in 2024
  • Find me on YouTube: Programmer Girl

Chapter 6: Additional Resources

The first video titled "NestJS with MongoDB & Mongoose - FULL BEGINNER TUTORIAL" offers a comprehensive guide on integrating NestJS with MongoDB.

The second video titled "Sign up form using Reactjs, Nestjs and mongo db | Node js | Part -1" provides insights into creating a sign-up form with React.js and Nest.js.

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

Autonomy: A Key Driver of Productivity and Customer Satisfaction

This study highlights how autonomy enhances productivity and customer satisfaction in software development, revealing impressive results.

A Dynamic 4-Minute Finish to Elevate Your Workout Experience

Discover an efficient 4-minute workout to enhance your fitness routine and maximize calorie burn while targeting major muscle groups.

Crafting Your Memoir: The Impact of Beta Readers on Your Writing

Discover how beta readers transformed Colby Coash's memoir, helping him uncover his defining moments and enhance his narrative.