Building a Simple CRUD API with Express and MongoDB

Photo by Remon Geo on Unsplash

Building a Simple CRUD API with Express and MongoDB

Building a Simple CRUD API with Express and MongoDB

In this blog post, we'll walk through a basic CRUD (Create, Read, Update, Delete) API built using Express.js and MongoDB. The code provided is a simple example, focusing on the essential operations to manage user data. We'll break down each CRUD operation.

Prerequisites

Before diving into the code, ensure you have Node.js and MongoDB installed on your machine.

Setting Up the Environment

const express = require("express");
const app = express();
const port = 3000;
app.use(express.json());
const mongoose = require("mongoose");

mongoose.connect("mongodb://localhost:27017/? Your Connection String from Mongodb Compaass");

Here, we're importing necessary modules, setting up an Express app, and connecting to a local MongoDB database using Mongoose.

Create Operation (POST /signup)

app.post("/signup", async (req, res) => {
  const username = req.body.username;
  const password = req.body.password;
  const name = req.body.name;

  const existingUser = await User.findOne({ email: username });

  if (existingUser) {
    return res.status(400).send("Username already exists");
  }

  const user = new User({
    name: name,
    email: username,
    password: password,
  });

  user.save();
  res.json({ message: "User created successfully" });
});

Here, we handle user signup. We check if the provided username (email) already exists in the database. If not, a new user is created using the User model, and the user data is saved to the database

Read Operation (GET /users)

app.get("/users", async (req, res) => {
  try {
    const users = await User.find();
    console.log(users);
    res.json({ title: "found users on your dataBase", users });
  } catch (error) {
    res.status(500).send("Server Error :(");
  }
});

This endpoint retrieves all users from the database using the User.find() method. If successful, it sends a JSON response containing the list of users.

Update Operation (PUT /users/:id)

app.put("/users/:id", async (req, res) => {
  try {
    const userId = req.params.id;
    const updatedUser = await User.findByIdAndUpdate(userId, req.body, { new: true });

    if (!updatedUser) {
      res.status(404).send(`User is not Found by ${userId}`);
    }

    res.json({ Message: "User Profile is Updated SuccessFully",
    user: updatedUser });
  } catch (error) {
    res.status(500).send("Internal Server Error :(");
  }
});

This endpoint updates a user's profile by finding the user with the specified ID (userId) and applying the updates provided in the request body.

Delete Operation (DELETE /users/:id)

app.delete("/users/:id", async (req, res) => {
  try {
    const userId = req.params.id;
    const deletedUser = await User.findByIdAndDelete(userId);

    if (!deletedUser) {
      res.status(404).send(`User not found of following id ${userId}`);
    }

    res.json({ message: "User deleted successfully" });
  } catch (error) {
    res.status(500).send("Internal Server Error ;(");
  }
});

This endpoint deletes a user by finding the user with the specified ID (userId) and removing it from the database.

In this blog post, we've explored a simple Express.js and MongoDB CRUD API for managing user data. Each operation, from creating a new user to deleting an existing one, has been explained in simple terms. Feel free to use and modify this code as a starting point for your own projects. Happy coding!