,

Building a CRUD-enabled simple todo app with NextJS and mongoDB

Posted by

CRUD in NextJS and mongoDB

CRUD in NextJS and mongoDB

Today, we’ll be discussing how to create a simple CRUD (Create, Read, Update, Delete) application using NextJS and mongoDB. We’ll be building a basic todo app to demonstrate the functionality.

Getting started with NextJS and mongoDB

First, make sure you have Node.js and npm installed on your machine. You can then create a new NextJS project using the following command:

    
      npx create-next-app@latest my-todo-app
      cd my-todo-app
    
  

Next, we’ll need to install the necessary dependencies for working with mongoDB in our NextJS app:

    
      npm install mongoose
    
  

Setting up mongoDB

Before we can start working on our todo app, we need to set up a mongoDB database. You can use a cloud-based service like MongoDB Atlas or set up a local instance of mongoDB on your machine.

Creating the todo model

Once our database is set up, we’ll need to define a mongoose model for our todo items. Create a new file called Todo.js in a models directory and add the following code:

    
      const mongoose = require('mongoose');

      const todoSchema = new mongoose.Schema({
        title: {
          type: String,
          required: true
        },
        completed: {
          type: Boolean,
          default: false
        }
      });

      const Todo = mongoose.model('Todo', todoSchema);

      module.exports = Todo;
    
  

Building the CRUD functionality

Now that our model is set up, we can start building the CRUD functionality in our NextJS app. We’ll create API routes for handling the CRUD operations on our todo items.

1. Creating a new todo

Create a new file called create.js in a pages/api/todo directory and add the following code:

    
      import dbConnect from '../../../utils/dbConnect';
      import Todo from '../../../models/Todo';

      dbConnect();

      export default async function handler(req, res) {
        const { method, body } = req;

        if(method === 'POST') {
          try {
            const todo = await Todo.create(body);
            res.status(201).json({ success: true, data: todo });
          } catch (error) {
            res.status(400).json({ success: false });
          }
        } else {
          res.status(405).json({ success: false });
        }
      }
    
  

2. Reading all todos

Create a new file called index.js in a pages/api/todo directory and add the following code:

    
      import dbConnect from '../../../utils/dbConnect';
      import Todo from '../../../models/Todo';

      dbConnect();

      export default async function handler(req, res) {
        const { method } = req;

        if(method === 'GET') {
          try {
            const todos = await Todo.find({});
            res.status(200).json({ success: true, data: todos });
          } catch (error) {
            res.status(400).json({ success: false });
          }
        } else {
          res.status(405).json({ success: false });
        }
      }
    
  

3. Updating a todo

Create a new file called update.js in a pages/api/todo directory and add the following code:

    
      import dbConnect from '../../../utils/dbConnect';
      import Todo from '../../../models/Todo';

      dbConnect();

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

        if(method === 'PUT') {
          try {
            const todo = await Todo.findByIdAndUpdate(query.id, body, { new: true, runValidators: true });
            if(!todo) {
              return res.status(400).json({ success: false });
            }
            res.status(200).json({ success: true, data: todo });
          } catch (error) {
            res.status(400).json({ success: false });
          }
        } else {
          res.status(405).json({ success: false });
        }
      }
    
  

4. Deleting a todo

Create a new file called delete.js in a pages/api/todo directory and add the following code:

    
      import dbConnect from '../../../utils/dbConnect';
      import Todo from '../../../models/Todo';

      dbConnect();

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

        if(method === 'DELETE') {
          try {
            const deletedTodo = await Todo.findByIdAndDelete(query.id);
            if(!deletedTodo) {
              return res.status(400).json({ success: false });
            }
            res.status(200).json({ success: true, data: {} });
          } catch (error) {
            res.status(400).json({ success: false });
          }
        } else {
          res.status(405).json({ success: false });
        }
      }
    
  

Testing the CRUD operations

Now that our CRUD functionality is set up, we can test it by creating, reading, updating, and deleting todo items in our app. You can use a tool like Postman or Insomnia to make requests to the API routes we’ve created.

Conclusion

In this article, we’ve explored how to implement basic CRUD functionality in a NextJS app using mongoDB as the database. We’ve created a simple todo app to demonstrate the CRUD operations, but you can apply these concepts to build more complex applications. Happy coding!

0 0 votes
Article Rating
6 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@DarkShadow00972
10 months ago

Thnx brother

@gauravr4127
10 months ago

I really enjoyed this video and found the information to be very helpful. However, I had a little trouble understanding the speaker at times. I think it would be helpful if the speaker spoke a little more slowly and enunciated more clearly. Overall, great video!

@magicalmind5278
10 months ago

src directory vs app directory ??

@codewithsam7300
10 months ago

Is this done with latest version of next js????

@swapnilpatel3337
10 months ago

Ab to app directory me video banao latest feature ke sath please

@michikibaruah5370
10 months ago

Good