Skip to content

Get All Todos Enpoint

First endpoint we will create will be the one that will return the list of all todo items from the database as an array. If there are no any todo items in the database, it should return an empty array.

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.get('/', (req, res) => {
  res.send('Hello World!');
});

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}`);
});
As you can se we added a new /todos GET endpoint that queries the database and returns the list of all todos found. If you restart your application now and go to http://localhost:3001/todos, you should see something like

{"data":[]}

That means that our code works fine, but we still do not have any todos added to the database.