Skip to content

Delete Todo Endpoint

After we added endpoints that will return list of all todo items from the database and one for adding a new item, we want to be able to delete items by providing their id.

For this, we will update our index.js file and add DELETE method.

const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const bodyParser = require('body-parser');
const app = express();
const port = 3001;

app.use(cors({origin: '*'}));
app.use(bodyParser.json());

const mongoDBLink = 'mongodb+srv://test_user:Test12345@cluster0.axh68.mongodb.net/todo_list?retryWrites=true&w=majority';

mongoose.connect(mongoDBLink);

const TodoModel = mongoose.model('Todo', new mongoose.Schema({ title: String, is_done: Boolean }));

app.post('/todo', async (req, res) => {
  const { title } = req.body;

  if (!title) {
    return res.status(400).json({
      message: 'Title value cannot be empty.',
    })
  }

  try {
    const todo = new TodoModel({
      title: title,
      is_done: false,
    });

    const newTodo = await todo.save();

    return res.status(200).json({
      todo: newTodo,
    })
  } catch (e) {
    return res.status(500).json({
      message: e.message,
    })
  }
});

app.get('/todos', async (req, res) => {
  try {
    const todos = await TodoModel.find();

    return res.status(200).json({
      data: todos,
    })
  } catch (e) {
    return res.status(500).json({
      message: e.message,
    })
  }
});

app.delete('/todo/:id', async (req, res) => {
  const { id } = req.params;

  if (!id || !mongoose.Types.ObjectId.isValid(id)) {
    return res.status(400).json({
      message: 'Valid ID must be provided.',
    })
  }

  try {
    const todo = await TodoModel.findById(id);

    if (!todo) {
      return res.status(400).json({
        message: 'Todo not found.',
      })
    }

    await todo.delete();

    return res.status(200).json({})
  } catch (e) {
    return res.status(500).json({
      message: e.message,
    })
  }
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
});

As you can see, we added a new method that will be responsible for deleting our todo items based on passed id of the specific item. You also notice that we covered a few cases where it should return an error.

First, we make sure the item id is provided as a parameter and it is a valid MongoDB id.

const { id } = req.params;

if (!id || !mongoose.Types.ObjectId.isValid(id)) {
    return res.status(400).json({
      message: 'Valid ID must be provided.',
    })
}

Also, we want to check if todo item we want to delete exists. If not, we will return an error an let user know that it does not.

const todo = await TodoModel.findById(id);

if (!todo) {
    return res.status(400).json({
        message: "Todo not found.",
    });
}

Then, we simply call a delete() function if item is found that should delete it from the database and return a successful response after it is done.

Cool! Now lets restart our application and in the next part try if our endpoint works as expected.