Prince Kumar Singh
Chocolate ๐Ÿซ aur code ๐Ÿง‘โ€๐Ÿ’ป

Follow

Chocolate ๐Ÿซ aur code ๐Ÿง‘โ€๐Ÿ’ป

Follow
TODO App Backend in EXPRESS

TODO App Backend in EXPRESS

Prince Kumar Singh's photo
Prince Kumar Singh
ยทJan 1, 2023ยท

2 min read

To build a todo application with the MERN stack (MongoDB, Express, React, and Node.js), follow these steps:

Create a MongoDB database and a collection to store to-do items.

Using Express, create a Node.js server and connect it to the MongoDB database.

Using Express routes and the MongoDB driver, create a set of API endpoints for creating, reading, updating, and deleting todo items.

Build a React frontend for the todo app.

To display the todo list and create new todo items, use React components.

To send HTTP requests to the API endpoints from the React frontend, use Axios or a similar library.

Add the ability to mark to-do items as completed and delete them.

Here's some code to get you started.

const express = require('express');
const router = express.Router();
const mongodb = require('mongodb');

// Connect to the MongoDB database
mongodb.MongoClient.connect('mongodb://localhost:27017', function(err, client) {
  if (err) throw err;

  const db = client.db('todos');

  // Create a todo item
  router.post('/todos', function(req, res) {
    const todo = {
      text: req.body.text,
      completed: false
    };

    db.collection('todos').insertOne(todo, function(err, result) {
      if (err) throw err;
      res.send(result.ops[0]);
    });
  });

  // Get all todo items
  router.get('/todos', function(req, res) {
    db.collection('todos').find().toArray(function(err, todos) {
      if (err) throw err;
      res.send(todos);
    });
  });

  // Update a todo item
  router.put('/todos/:id', function(req, res) {
    const id = new mongodb.ObjectID(req.params.id);
    const todo = {
      text: req.body.text,
      completed: req.body.completed
    };

    db.collection('todos').updateOne({ _id: id }, { $set: todo }, function(err, result) {
      if (err) throw err;
      res.send(result);
    });
  });

  // Delete a todo item
  router.delete('/todos/:id', function(req, res) {
    const id = new mongodb.ObjectID(req.params.id);
    db.collection('todos').deleteOne({ _id: id }, function(err, result) {
      if (err) throw err;
      res.send(result);
    });
  });
});

module.exports = router;
ย 
Share this