Build a CRUD App with Node.js, MongoDB, and Next.js


To implement a basic CRUD (Create, Read, Update, Delete) application in Node.js using Next.js and MongoDB, follow these steps:

Step 1: Set up a Next.js project

  1. Create a Next.js project (if you haven't already):

    npx create-next-app@latest nextjs-mongo-crud
    cd nextjs-mongo-crud
  2. Install necessary dependencies:

    npm install mongoose

Step 2: Set up MongoDB connection

  1. Create a .env.local file in the root of your project and add your MongoDB connection string:

    MONGODB_URI=mongodb://localhost:27017/your-database-name
  2. Create a utility file to manage the MongoDB connection. Create a new file lib/mongodb.js:

    import mongoose from 'mongoose';
    
    const connectToDatabase = async () => {
      if (mongoose.connection.readyState >= 1) {
        return;
      }
    
      await mongoose.connect(process.env.MONGODB_URI, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
      });
    };
    
    export default connectToDatabase;

Step 3: Create a Mongoose Model

Define a model for the data you want to store in MongoDB. For example, let's create a simple model for User.

Create a new file models/User.js:

import mongoose from 'mongoose';

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
    unique: true,
  },
});

const User = mongoose.models.User || mongoose.model('User', userSchema);

export default User;

Step 4: Create API Routes for CRUD Operations

Next.js allows you to create API routes easily. Here’s how you can implement the CRUD operations.

1. Create User (/pages/api/users/create.js)

import connectToDatabase from '../../../lib/mongodb';
import User from '../../../models/User';

export default async function handler(req, res) {
  if (req.method === 'POST') {
    try {
      await connectToDatabase();

      const { name, email } = req.body;

      const newUser = new User({ name, email });
      await newUser.save();

      res.status(201).json(newUser);
    } catch (error) {
      res.status(500).json({ error: 'Failed to create user' });
    }
  } else {
    res.status(405).json({ error: 'Method not allowed' });
  }
}

2. Read Users (/pages/api/users/index.js)

import connectToDatabase from '../../../lib/mongodb';
import User from '../../../models/User';

export default async function handler(req, res) {
  if (req.method === 'GET') {
    try {
      await connectToDatabase();

      const users = await User.find({});
      res.status(200).json(users);
    } catch (error) {
      res.status(500).json({ error: 'Failed to fetch users' });
    }
  } else {
    res.status(405).json({ error: 'Method not allowed' });
  }
}

3. Update User (/pages/api/users/[id].js)

import connectToDatabase from '../../../lib/mongodb';
import User from '../../../models/User';

export default async function handler(req, res) {
  const { id } = req.query;

  if (req.method === 'PUT') {
    try {
      await connectToDatabase();

      const { name, email } = req.body;

      const updatedUser = await User.findByIdAndUpdate(
        id,
        { name, email },
        { new: true }
      );

      if (!updatedUser) {
        return res.status(404).json({ error: 'User not found' });
      }

      res.status(200).json(updatedUser);
    } catch (error) {
      res.status(500).json({ error: 'Failed to update user' });
    }
  } else {
    res.status(405).json({ error: 'Method not allowed' });
  }
}

4. Delete User (/pages/api/users/[id].js)

import connectToDatabase from '../../../lib/mongodb';
import User from '../../../models/User';

export default async function handler(req, res) {
  const { id } = req.query;

  if (req.method === 'DELETE') {
    try {
      await connectToDatabase();

      const deletedUser = await User.findByIdAndDelete(id);

      if (!deletedUser) {
        return res.status(404).json({ error: 'User not found' });
      }

      res.status(200).json({ message: 'User deleted' });
    } catch (error) {
      res.status(500).json({ error: 'Failed to delete user' });
    }
  } else {
    res.status(405).json({ error: 'Method not allowed' });
  }
}

Step 5: Test CRUD Operations

  1. Create a user:

    Send a POST request to /api/users/create with the user data in the body:

    {
      "name": "John Doe",
      "email": "john@example.com"
    }
  2. Read users:

    Send a GET request to /api/users.

  3. Update a user:

    Send a PUT request to /api/users/[id] with the updated data in the body:

    {
      "name": "John Smith",
      "email": "john.smith@example.com"
    }
  4. Delete a user:

    Send a DELETE request to /api/users/[id].

Step 6: Run the Application

Now, run the Next.js application:

npm run dev

You can access the API routes and interact with the MongoDB database to perform CRUD operations.

This is a basic setup for a CRUD app using Next.js and MongoDB. You can extend it with features like validation, authentication, and error handling as needed.

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete