DEV Community

Cover image for GET, POST, PUT and DELETE Todos from the database using MongoDB
Aneeqa Khan
Aneeqa Khan

Posted on • Updated on

GET, POST, PUT and DELETE Todos from the database using MongoDB

Table Of Contents

For this series, I'm following an excellent video tutorial from Traversy Media

Create a model

Create a new folder models inside a backend folder and create a new file named todoModel.js inside it. In this file, I'll make a schema of the todos resources.



const mongoose = require('mongoose');

const todoSchema = mongoose.Schema(
  {
    text: {
      type: String,
      required: [true, 'Please add a text value'],
    },
  },
  {
    timestamps: true,
  }
);

module.exports = mongoose.model('Todo', todoSchema);


Enter fullscreen mode Exit fullscreen mode

by setting timestamps: true, Mongoose will automatically create a createdAt and updatedAt fields.

Add todo

First I'll update the POST call in todosController.js file.



const Todo = require('../models/todoModel');

const setTodo = asyncHanlder(async (req, res) => {
  if (!req.body.text) {
    res.status(400);
    throw new Error('Please add text field');
  }
  const todo = await Todo.create({
    text: req.body.text,
  });
  res.status(200).json(todo);
})


Enter fullscreen mode Exit fullscreen mode

I'm using a create method of Mongoose and passing the text from the request body and returning the exact todo from the database.
On postman, it'll show like this

post-todo

Get todo

In the get todos function, I'll use find method of Mongoose. It'll get all of the todos added. Later I'll change it to get the todos by a specific user.



const getTodos = asyncHanlder(async (req, res) => {
  const todos = await Todo.find();
  res.status(200).json(todos)
});


Enter fullscreen mode Exit fullscreen mode

On postman, it'll show like this

get-todo

Update todo

In the update todos function, I'll use findByIdAndUpdate method to update the already added todo.



const updateTodo = asyncHanlder(async (req, res) => {
  const todo = await Todo.findById(req.params.id);

  if (!todo) {
    res.status(400);
    throw new Error('Todo not found');
  }

  const updatedTodo = await Todo.findByIdAndUpdate(req.params.id, req.body, {
    new: true,
  });

  res.status(200).json(updatedTodo);
})


Enter fullscreen mode Exit fullscreen mode

and the result will be like this

update-todo

Delete todo

For delete todo, I'll first get the todo by finding the id and then use the remove method to delete it.



const deleteTodo = asyncHanlder(async (req, res) => {
  const todo = await Todo.findById(req.params.id);

  if (!todo) {
    res.status(400);
    throw new Error('Todo not found');
  }

  await todo.remove();

  res.status(200).json({ id: req.params.id });
})


Enter fullscreen mode Exit fullscreen mode

On postman, it'll show like this

delete-todo

So that's how you can create your CRUD APIs in MongoDB by using Mongoose and Express.

Thank you for reading!
Feel free to connect on Twitter

Top comments (2)

Collapse
 
momin profile image
Md Abdul Momin

I couldn't find the mongoose remove() method! Here deleteOne() work

const deleteTodo = asyncHanlder(async (req, res) => {
  const todo = await Todo.findById(req.params.id);

  if (!todo) {
    res.status(400);
    throw new Error('Todo not found');
  }

  await todo.deleteOne();

  res.status(200).json({ id: req.params.id });
})
Enter fullscreen mode Exit fullscreen mode
Collapse
 
mayank_biswari profile image
mayab

await todo.remove(); is not working in deleteTodo() function you can replace it with "await Todo.deleteOne({_id: req.params.id});"