.NET  

Building a CRUD API with Express.js and MongoDB

Backend engineers should gain a thorough understanding of how to construct a RESTful CRUD API, which stands for construct, Read, Update, and Delete activities. This tutorial will guide you step-by-step through the process of creating a simple CRUD API with Node.js, Express.js, and MongoDB.

Let's make sure you're ready before we get started. What you must have installed is as follows:

  • Node.js
  • MongoDB
  • A code editor, like VS Code

Step 1. Open VS Code terminal and create a project folder

mkdir crud-app
cd crud-app

Step 2. Initialize your project

npm init -y

Step 3. Install the necessary dependencies

npm install express mongoose body-parser cors dotenv

Step 4. Create a project structure like below

Step 5. Ensure that the necessary dependencies are installed in package.json

package.json file

{
  "name": "crud-app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
 "scripts": {
    "start": "node index.js" 
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^2.2.0",
    "cors": "^2.8.5",
    "dotenv": "^16.5.0",
    "express": "^5.1.0",
    "mongoose": "^8.16.0"
  }
}

Step 6. Create an employeeModel.js inside the model folder

import mongoose from "mongoose";

const empSchema=new mongoose.Schema({
    name:{
        type:String,
        required: true
    },
     email:{
        type:String,
        required: true
    },
     address:{
        type:String,
        required: true
    }

})
export default mongoose.model("Employee",empSchema);

Step 7. Create an employeeController.js inside the controller folder

import Employee from "../model/employeeModel.js"

export const create = async (req,res)=>{
try
{
const empData=new Employee(req.body);
const {email}=empData;

const empExist = await Employee.findOne({email});
if(empExist){
    return res.status(400).json({message: "Employee already exists."});
}
const savedEmp=await empData.save();
res.status(200).json(savedEmp);
}
catch(error)
{
    req.status(500).json({error: "Internal Server Error"});
}
};

export const fetch=async (req,res)=>{
try
{
const employees=await Employee.find();
if(employees.length===0)
{
    return res.status(404).json({message: "Employee Not Found"});
}
res.status(200).json(employees);
}catch(error)
{
    res.status(500).json({error:"Internal Server error."})
}
};

export const update=async (req,res)=>{
    try
    {
    const id=req.params.id;
    const empExist =await Employee.findOne({_id:id})
    if(!empExist)
    {
        return res.status(404).json({message:"Employee Not Found"});
    }
    const updateEmp=await Employee.findByIdAndUpdate(id,req.body,{new:true})
    res.status(200).json(updateEmp);
    }
    catch(error)
    {
    res.status(500).json({error:"Internal Server error."})
    }
};

export const deleteEmployee = async (req,res)=>{
    try{
   const id=req.params.id;
   const empExist=Employee.findById({_id:id});
   if(!empExist)
   {
    res.status(404).json({message:"Employee not found"});
   }
   await Employee.findByIdAndDelete(id);
   res.status(200).json({message:"Employee deleted successfully"});
    }
    catch(error)
    {
    res.status(500).json({message:"Internal server error"});
    }
};

Step 8. Create an EmployeeRoutes.js inside the routes folder

import express from "express"
import { fetch, create, update,deleteEmployee } from "../controller/employeeController.js"

const route=express.Router();
route.post("/create",create);
route.get("/getallemployees",fetch);
route.put("/update/:id",update);
route.delete("/deleteemployee/:id",deleteEmployee);
export default route;

Step 9. Go to your project root directory and create a .env file

PORT=8001
MONGO_URL="mongodb://localhost:27017/crud-app"

Step 10. Go to your project root directory and create an index.js file

import express from "express";
import mongoose from "mongoose";
import bodyParser from "body-parser";
import dotenv from "dotenv";
import cors from "cors"; 
import route from "./routes/EmployeeRoutes.js";

dotenv.config();

const app = express();

// Middleware
app.use(cors()); 
app.use(bodyParser.json());

const PORT = process.env.PORT || 5000;
const MONGOURL = process.env.MONGO_URL;

mongoose.connect(MONGOURL)
  .then(() => {
    console.log("Database connection successful");
    app.listen(PORT, () => {
      console.log(`Server is running on port ${PORT}`);
    });
  })
  .catch((error) => {
    console.error("MongoDB connection error:", error);
  });

app.use("/api/employee", route);

Step 11. Developers now use Postman as their go-to tool for testing API endpoints. Because it supports every HTTP method-GET, POST, PUT, DELETE, and more-it is very popular.

Step 12. Test your API endpoint.

Create a New Employee

  • Method: POST
  • URL: http://localhost:8001/api/employee/create
  • Body (JSON):
    {
        "name":"kripanshu",
        "email": "[email protected]",
        "address":"Noida,India"
    }

Get All Employees

  • Method: GET
  • URL: http://localhost:8001/api/employee/getallemployees

Update an Employee by ID

  • Method: PUT
  • URL: http://localhost:8001/api/employee/update/:id
  • Replace: id with the actual employee ID.
  • Body (JSON):
    {
        "name":"deepanshu",
        "email": "[email protected]",
        "address":"Delhi,India"
    }

Delete an Employee by ID

  • Method: DELETE
  • URL: http://localhost:8001/api/employee/deleteemployee/:id
  • Replace: id with the actual employee ID.
    Postman is being used to test a POST Request to a RESTful API endpoint.
    Postman