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);
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);
})
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
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)
});
On postman, it'll show like this
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);
})
and the result will be like this
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 });
})
On postman, it'll show like this
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