In this tutorial, we'll walk through the process of creating a simple yet powerful To-Do List application using Node.js, Express, and MongoDB. These technologies allow us to build a robust backend for our application, providing features like creating, retrieving, updating, and deleting to-do items.
Prerequisites
Before we begin, make sure you have the following installed:
- Node.js and npm: Download and Install Node.js
- MongoDB: Install MongoDB
Setting up the Project
Let's start by setting up the project structure and configuring the dependencies.
1. Project Structure
Create the following project structure:
project-root
|-- server.js
|-- models
| |-- todo.model.js
|-- routes
| |-- todo.route.js
2. Dependencies
Install the required packages by running the following command:
npm init -y
npm install express mongoose
Creating the Todo Model
In models/todo.model.js
, define the schema for our to-do items:
// models/todo.model.js
import mongoose from 'mongoose';
const todoSchema = new mongoose.Schema(
{
title: {
type: String,
required: true,
},
completed: {
type: Boolean,
default: false,
},
},
{
timestamps: true,
}
);
const Todo = mongoose.model('Todo', todoSchema);
export default Todo;
This schema includes a title
(the to-do item's name) and a completed
flag to indicate whether the task is completed or not.
Creating the Todo Routes
In routes/todo.route.js
, define the routes for creating, retrieving, updating, and deleting to-do items:
// routes/todo.route.js
import express from 'express';
import Todo from '../models/todo.model.js';
const router = express.Router();
// Create a new todo
router.post('/', async (req, res) => {
try {
const todo = new Todo({
title: req.body.title,
completed: req.body.completed,
});
await todo.save();
res.status(201).json(todo);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
// Get all todos
router.get('/', async (req, res) => {
try {
const todos = await Todo.find();
res.json(todos);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
// Update a todo
router.patch('/:id', async (req, res) => {
try {
const todo = await Todo.findById(req.params.id);
if (todo) {
todo.completed = req.body.completed;
await todo.save();
res.json(todo);
} else {
res.status(404).json({ error: 'Todo not found' });
}
} catch (error) {
res.status(400).json({ error: error.message });
}
});
// Delete a todo
router.delete('/:id', async (req, res) => {
try {
const todo = await Todo.findById(req.params.id);
if (todo) {
await todo.deleteOne();
res.json({ message: 'Todo removed' });
} else {
res.status(404).json({ error: 'Todo not found' });
}
} catch (error) {
res.status(400).json({ error: error.message });
}
});
export default router;
These routes handle CRUD (Create, Read, Update, Delete) operations for our to-do items.
Configuring the Server
In server.js
, configure the server and connect to MongoDB:
// server.js
import express from 'express';
import mongoose from 'mongoose';
import todoRoutes from './routes/todo.route.js';
const app = express();
const PORT = process.env.PORT || 3000;
mongoose
.connect('your_mongoDB_connection_string_here', {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log('Connected to MongoDB');
})
.catch((error) => {
console.log('Error:', error);
});
app.use(express.json());
app.use('/api/todos', todoRoutes);
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Replace 'your_mongoDB_connection_string_here'
with your actual MongoDB connection string.
Testing the Application
Now, you can start your server:
node server.js
Your API will be accessible at http://localhost:3000/api/todos
. Use tools like Postman or your preferred API testing tool to send requests to these endpoints.
Congratulations! You've successfully built a To-Do List application using Node.js, Express, and MongoDB. Feel free to enhance and customize the application based on your requirements.
Explore a full-stack To-Do List app built with MERN stack and TypeScript. The frontend, developed in React, and the backend, implemented in Node.js, offer a comprehensive development experience. Check out the GitHub repository. Feel free to reach out ME if you have any questions! ๐