Skip to content

Add New Todo Endpoint

Let's make a POST endpoint responsible for adding our todos to the database.

const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const app = express();
const port = 3001;

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

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;

  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.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
});

Our /todo POST endpoint expects title to be sent from client side in order to add a new todo to the database.

But, the one thing that is missing above is validation of the title value. We do not want to allow todos with empty titles so let's add that validation.

const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const app = express();
const port = 3001;

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

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.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
});

We also need to intall body-parser library so we can parse query and body data from requests properly. To do that you need to execute

npm install --save body-parser

After that, we need to modify index.js in order to add body-parser to expres requests

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.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
});

Cool! We now need to restart our application and in the next part test if adding our todos works properly.