GET, POST, PUT and DELETE Todos from the database using MongoDB
Tags: node, javascript, beginners
Published: 2022-12-23 10:51:14

## Table Of Contents
  * [Create a model](#model)
  * [Add todo](#add-todo)
  * [Get todo](#get-todo)
  * [Update todo](#update-todo)
  * [Delete todo](#delete-todo)

> *For this series, I'm following an excellent video tutorial from [Traversy Media](https://www.youtube.com/playlist?list=PLillGF-RfqbbQeVSccR9PGKHzPJSWqcsm)*

### Create a model <a name="model"></a>
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.
```javascript
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);
```
by setting `timestamps: true`, Mongoose will automatically create a `createdAt` and `updatedAt` fields.

### Add todo <a name="add-todo"></a>
First I'll update the POST call in `todosController.js` file.
```javascript
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);
})
```
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p39tbkjgamp38lsp13gf.png)

### Get todo <a name="get-todo"></a>
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.
```javascript
const getTodos = asyncHanlder(async (req, res) => {
  const todos = await Todo.find();
  res.status(200).json(todos)
});
```
On postman, it'll show like this

![get-todo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2am6qmktm1qact01fxmm.png)

### Update todo <a name="update-todo"></a>
In the update todos function, I'll use `findByIdAndUpdate` method to update the already added todo.
```javascript
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);
})
```
and the result will be like this

![update-todo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/toek59lhbfuqruso1iia.png)
 
### Delete todo <a name="delete-todo"></a>
For delete todo, I'll first get the todo by finding the id and then use the `remove` method to delete it.
```javascript
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 });
})
```
On postman, it'll show like this

![delete-todo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tkg6yqjaopf9k1yj4nzv.png)

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](https://twitter.com/Aneeqa_Khan25)