Build a Simple Task Manager With Categories Using Node.js and MongoDB
Introduction
Managing daily tasks efficiently is essential for individuals, students, developers, and businesses. Whether you are working on multiple projects, managing personal activities, or coordinating with a team, keeping track of tasks can become challenging without a proper system.
A Task Manager Application helps users organize their activities, set priorities, track progress, and manage deadlines from a single platform. Adding categories makes the application even more useful because users can group tasks based on different areas, such as Work, Personal, Education, Development, and Meetings.
In this tutorial, we will learn how to build a simple Task Manager with Categories using Node.js and MongoDB. We will create a backend application that allows users to add, view, update, delete, and categorize tasks.
We will use Node.js and Express.js to build REST APIs and MongoDB to store task information. Mongoose will help us define schemas, validate data, and interact with the database.
By the end of this tutorial, you will understand how these technologies work together to build a practical application.
1. What Are We Going to Build?
Our project will be a simple task management system with category-based organization.
Users will be able to:
-
Create new tasks with titles and descriptions.
-
Assign categories to tasks.
-
Set task priorities.
-
Add due dates.
-
Track task status.
-
Update existing tasks.
-
Delete completed or unnecessary tasks.
-
Filter tasks based on categories and status.
Example application structure
Imagine a user managing the following tasks:
| Task | Category | Priority | Status |
|---|---|---|---|
| Complete Node.js project | Development | High | Pending |
| Prepare monthly report | Work | Medium | In Progress |
| Study MongoDB | Education | High | Completed |
| Buy groceries | Personal | Low | Pending |
Instead of keeping everything in one list, categories help users find specific tasks quickly.
2. Technologies Required
Before starting development, let’s understand the technologies used in this project.
Node.js
Node.js is a JavaScript runtime that allows developers to execute JavaScript outside the browser.
In this project, Node.js will handle backend operations such as:
-
Processing user requests.
-
Managing application logic.
-
Communicating with MongoDB.
-
Performing CRUD operations.
-
Returning responses through REST APIs.
Express.js
Express.js is a lightweight web framework for Node.js.
It simplifies backend development by providing routing, middleware, and request-handling functionality.
We will use Express.js to create APIs such as:
-
POST /api/tasks -
GET /api/tasks -
PUT /api/tasks/:id -
DELETE /api/tasks/:id
MongoDB
MongoDB is a NoSQL database that stores information in flexible BSON documents.
We will use MongoDB to store task details, categories, priorities, due dates, and task statuses.
Mongoose
Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js.
It provides:
-
Schema definitions.
-
Data validation.
-
Model creation.
-
Database queries.
-
Relationships between collections.
3. Understanding the Application Architecture
Before writing code, it is important to understand how different components communicate.
The application follows a simple three-layer architecture:
-
Client Layer: Sends requests to create, update, view, or delete tasks.
-
Backend Layer: Node.js and Express.js process requests and execute business logic.
-
Database Layer: MongoDB stores task and category information.
How does it work?
For example, when a user creates a new task:
-
The user enters a task title, description, category, and priority.
-
The frontend sends a POST request to the Express API.
-
Express receives the request and validates the input.
-
Mongoose communicates with MongoDB.
-
MongoDB stores the new task document.
-
The backend returns a success response.
This process allows the frontend and backend to communicate without directly accessing the database.
4. Setting Up the Node.js Project
Let’s start building the application.
First, make sure the following software is installed:
-
Node.js
-
MongoDB Community Server or MongoDB Atlas
-
Visual Studio Code
-
Postman (for API testing)
Step 1: Create a project directory
Open your terminal and execute:
mkdir task-manager
cd task-manager
Initialize the Node.js project:
npm init -y
This command creates a package.json file that stores project information and dependencies.
Step 2: Install required dependencies
Run the following command:
npm install express mongoose dotenv cors
Install Nodemon as a development dependency:
npm install --save-dev nodemon
Purpose of each package:
| Package | Purpose |
|---|---|
| express | Creates REST APIs |
| mongoose | Connects Node.js with MongoDB |
| dotenv | Manages environment variables |
| cors | Enables cross-origin requests |
| nodemon | Automatically restarts the server during development |
Step 3: Create the project structure
Organize your project into separate folders to make the application easier to maintain.
task-manager/
│
├── config/
│ └── database.js
│
├── models/
│ ├── Task.js
│ └── Category.js
│
├── routes/
│ ├── taskRoutes.js
│ └── categoryRoutes.js
│
├── .env
├── server.js
├── package.json
└── node_modules/
This structure separates database configuration, models, routes, and application logic.
5. Connecting Node.js With MongoDB
Now let’s establish a connection between our Node.js application and MongoDB.
Step 1: Configure environment variables
Create a .env file in the project root directory.
PORT=5000
MONGO_URI=mongodb://127.0.0.1:27017/taskmanager
Here:
-
PORTdefines the application server port. -
MONGO_URIspecifies the MongoDB connection string. -
taskmanageris the database name.
If you are using MongoDB Atlas, replace the local connection string with your Atlas connection string.
Never commit your .env file or expose database credentials in public repositories.
Step 2: Create database configuration
Create config/database.js.
const mongoose = require("mongoose");
const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGO_URI);
console.log("MongoDB Connected Successfully");
} catch (error) {
console.error("MongoDB Connection Failed:", error.message);
process.exit(1);
}
};
module.exports = connectDB;
Explanation:
-
mongoose.connect()establishes the database connection. -
process.env.MONGO_URIreads the connection string. -
try...catchhandles connection errors. -
process.exit(1)stops the application if the initial database connection fails.
6. Creating the Category Model
Categories help users organize tasks based on their purpose.
For example:
-
Work
-
Personal
-
Education
-
Development
-
Meetings
Instead of storing category names repeatedly inside every task, we will create a separate Category collection.
Create models/Category.js.
const mongoose = require("mongoose");
const categorySchema = new mongoose.Schema(
{
name: {
type: String,
required: true,
unique: true,
trim: true
},
description: {
type: String,
default: ""
}
},
{
timestamps: true
}
);
module.exports = mongoose.model("Category", categorySchema);
Understanding the Category Schema
| Field | Description |
|---|---|
| name | Stores the category name |
| description | Provides additional information |
| createdAt | Records when the category was created |
| updatedAt | Records the latest update |
The unique: true option creates a uniqueness constraint through a MongoDB index, helping prevent duplicate category names.
The timestamps: true option automatically manages creation and update timestamps.
7. Creating the Task Model
Now we need a Task model to store individual tasks.
Each task will contain:
-
Title
-
Description
-
Category
-
Priority
-
Status
-
Due date
Create models/Task.js.
const mongoose = require("mongoose");
const taskSchema = new mongoose.Schema(
{
title: {
type: String,
required: true,
trim: true
},
description: {
type: String,
default: ""
},
category: {
type: mongoose.Schema.Types.ObjectId,
ref: "Category",
required: true
},
priority: {
type: String,
enum: ["Low", "Medium", "High"],
default: "Medium"
},
status: {
type: String,
enum: ["Pending", "In Progress", "Completed"],
default: "Pending"
},
dueDate: {
type: Date,
default: null
}
},
{
timestamps: true
}
);
module.exports = mongoose.model("Task", taskSchema);
How does the category relationship work?
Notice the following code:
category: {
type: mongoose.Schema.Types.ObjectId,
ref: "Category",
required: true
}
This creates a reference to a document in the Category collection.
For example, a category document might look like this:
{
"_id": "672a12345678901234567890",
"name": "Development",
"description": "Programming-related tasks"
}
A task can reference this category using its ObjectId.
This approach avoids repeatedly storing category descriptions inside every task.
8. Building Category APIs
Now let’s create APIs to add and retrieve categories.
Create routes/categoryRoutes.js.
const express = require("express");
const router = express.Router();
const Category = require("../models/Category");
// Create Category
router.post("/", async (req, res) => {
try {
const { name, description } = req.body;
if (!name || !name.trim()) {
return res.status(400).json({
message: "Category name is required"
});
}
const category = await Category.create({
name,
description
});
res.status(201).json({
message: "Category created successfully",
category
});
} catch (error) {
if (error.code === 11000) {
return res.status(409).json({
message: "Category already exists"
});
}
res.status(500).json({
message: "Server error",
error: error.message
});
}
});
// Get All Categories
router.get("/", async (req, res) => {
try {
const categories = await Category.find().sort({
name: 1
});
res.status(200).json(categories);
} catch (error) {
res.status(500).json({
message: error.message
});
}
});
module.exports = router;
Available Category APIs
| Method | Endpoint | Purpose |
|---|---|---|
| POST | /api/categories |
Create category |
| GET | /api/categories |
Retrieve all categories |
Example category request:
{
"name": "Development",
"description": "Programming and coding tasks"
}
The API creates a new category and returns its MongoDB document.
9. Building Task Management APIs
This is the most important part of our project.
We will create APIs to perform CRUD operations:
-
Create tasks.
-
Read tasks.
-
Update tasks.
-
Delete tasks.
-
Filter tasks by category and status.
Create routes/taskRoutes.js.
Step 1: Create a new task
const express = require("express");
const router = express.Router();
const Task = require("../models/Task");
const Category = require("../models/Category");
// Create Task
router.post("/", async (req, res) => {
try {
const {
title,
description,
category,
priority,
dueDate
} = req.body;
if (!title || !title.trim() || !category) {
return res.status(400).json({
message: "Title and category are required"
});
}
const categoryExists = await Category.findById(category);
if (!categoryExists) {
return res.status(404).json({
message: "Category not found"
});
}
const task = await Task.create({
title,
description,
category,
priority,
dueDate
});
res.status(201).json({
message: "Task created successfully",
task
});
} catch (error) {
res.status(500).json({
message: error.message
});
}
});
This API receives task information, verifies that the category exists, and saves the new task in MongoDB.
Example request:
{
"title": "Complete Node.js Project",
"description": "Finish the backend development",
"category": "672a12345678901234567890",
"priority": "High",
"dueDate": "2026-11-15"
}
Step 2: Retrieve all tasks
Add the following API:
// Get All Tasks
router.get("/", async (req, res) => {
try {
const tasks = await Task.find()
.populate("category", "name description")
.sort({ createdAt: -1 });
res.status(200).json(tasks);
} catch (error) {
res.status(500).json({
message: error.message
});
}
});
Here, we use an important Mongoose feature called populate().
Without population, the category field contains only its ObjectId.
With populate(), MongoDB-related category information is included in the response.
Example response:
{
"title": "Complete Node.js Project",
"description": "Finish the backend development",
"category": {
"_id": "672a12345678901234567890",
"name": "Development",
"description": "Programming and coding tasks"
},
"priority": "High",
"status": "Pending"
}
Step 3: Retrieve a task by ID
// Get Task By ID
router.get("/:id", async (req, res) => {
try {
const task = await Task.findById(req.params.id)
.populate("category", "name");
if (!task) {
return res.status(404).json({
message: "Task not found"
});
}
res.status(200).json(task);
} catch (error) {
res.status(400).json({
message: "Invalid task ID or request"
});
}
});
This API allows users to retrieve an individual task using its MongoDB ObjectId.
Step 4: Update an existing task
// Update Task
router.put("/:id", async (req, res) => {
try {
const task = await Task.findByIdAndUpdate(
req.params.id,
req.body,
{
new: true,
runValidators: true
}
).populate("category", "name");
if (!task) {
return res.status(404).json({
message: "Task not found"
});
}
res.status(200).json({
message: "Task updated successfully",
task
});
} catch (error) {
res.status(400).json({
message: error.message
});
}
});
The findByIdAndUpdate() method updates the selected task.
Important options:
-
new: truereturns the updated document. -
runValidators: trueapplies schema validation during the update.
For production applications, it is also important to whitelist accepted update fields rather than passing the entire request body directly.
Step 5: Delete a task
// Delete Task
router.delete("/:id", async (req, res) => {
try {
const task = await Task.findByIdAndDelete(
req.params.id
);
if (!task) {
return res.status(404).json({
message: "Task not found"
});
}
res.status(200).json({
message: "Task deleted successfully"
});
} catch (error) {
res.status(400).json({
message: error.message
});
}
});
This API permanently deletes a task from the database.
Step 6: Filter tasks by category and status
One of the most useful features of a task manager is filtering.
For example, users may want to see only:
-
Development tasks.
-
Completed tasks.
-
High-priority tasks.
-
Pending personal activities.
Add this route before the /:id routes in taskRoutes.js.
// Filter Tasks
router.get("/filter/search", async (req, res) => {
try {
const { category, status, priority } = req.query;
const filter = {};
if (category) {
filter.category = category;
}
if (status) {
filter.status = status;
}
if (priority) {
filter.priority = priority;
}
const tasks = await Task.find(filter)
.populate("category", "name")
.sort({ createdAt: -1 });
res.status(200).json(tasks);
} catch (error) {
res.status(400).json({
message: error.message
});
}
});
module.exports = router;
Example API requests:
GET /api/tasks/filter/search?status=Completed
GET /api/tasks/filter/search?priority=High
GET /api/tasks/filter/search?category=672a12345678901234567890
You can also combine multiple filters:
GET /api/tasks/filter/search?status=Pending&priority=High
This makes it easier to retrieve only the tasks that match specific conditions.
10. Creating the Main Server File
We have created the database configuration, models, and API routes. Now we need to connect everything through the main application file.
Open server.js and add:
const express = require("express");
const dotenv = require("dotenv");
const cors = require("cors");
const connectDB = require("./config/database");
dotenv.config();
const app = express();
// Middleware
app.use(cors());
app.use(express.json());
// Database Connection
connectDB();
// Routes
app.use("/api/tasks", require("./routes/taskRoutes"));
app.use("/api/categories", require("./routes/categoryRoutes"));
// Home Route
app.get("/", (req, res) => {
res.send("Task Manager API is Running");
});
// Start Server
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
The main server file performs the following operations:
-
Imports the required packages.
-
Loads environment variables.
-
Configures middleware.
-
Connects to MongoDB.
-
Registers API routes.
-
Starts the Express server.
Update the scripts section in package.json:
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js"
}
Start the application:
npm run dev
If everything is configured correctly, you should see:
MongoDB Connected Successfully
Server running on port 5000
Your backend application is now running.
11. Testing the APIs Using Postman
Before connecting a frontend, we should test all API endpoints.
Postman is a popular tool for testing REST APIs.
Use the following endpoints:
| Operation | HTTP Method | Endpoint |
|---|---|---|
| Create category | POST | /api/categories |
| Get categories | GET | /api/categories |
| Create task | POST | /api/tasks |
| Get all tasks | GET | /api/tasks |
| Get task by ID | GET | /api/tasks/:id |
| Update task | PUT | /api/tasks/:id |
| Delete task | DELETE | /api/tasks/:id |
| Filter tasks | GET | /api/tasks/filter/search |
For POST and PUT requests, select:
Body → raw → JSON
Enter the appropriate JSON request body and click Send.
Verify that the API returns the correct HTTP status code and response.
12. Understanding the MongoDB Database Structure
Let’s look at how the information is stored in MongoDB.
Our application uses two collections:
Categories collection
{
"_id": "672a12345678901234567890",
"name": "Development",
"description": "Programming tasks"
}
Tasks collection
{
"_id": "672b12345678901234567890",
"title": "Build Task Manager",
"description": "Develop a Node.js application",
"category": "672a12345678901234567890",
"priority": "High",
"status": "In Progress",
"dueDate": "2026-11-15T00:00:00.000Z"
}
The Task collection stores the category ObjectId as a reference to the Categories collection.
This structure makes category management more flexible and avoids unnecessary duplication of category information.
13. Improving Application Performance With MongoDB Indexing
As the number of tasks increases, retrieving and filtering records can become slower if the database does not have appropriate indexes.
MongoDB indexing helps improve query performance by reducing the amount of data that needs to be examined.
For example, if users frequently filter tasks based on status and category, we can create a compound index.
Add this to models/Task.js before exporting the model:
taskSchema.index({
category: 1,
status: 1
});
This index can help queries that filter by category and status together, and queries that filter by category alone.
You can also create an index for priority:
taskSchema.index({
priority: 1
});
To inspect indexes in MongoDB:
db.tasks.getIndexes()
To analyze query performance:
db.tasks.find({
status: "Pending"
}).explain("executionStats")
Pay attention to:
-
nReturned: Number of documents returned. -
totalDocsExamined: Number of documents examined. -
totalKeysExamined: Number of index keys examined. -
executionTimeMillis: Query execution time.
Remember that indexes consume storage and add overhead to insert, update, and delete operations. Create indexes based on actual query patterns rather than indexing every field.
14. Additional Features to Make the Application Better
Once the basic application is working, we can extend it with additional functionality.
1. Due Date Management
Allow users to assign deadlines and identify overdue tasks. This helps users complete important activities on time.
2. Priority Management
Add High, Medium, and Low priority levels to help users identify important tasks.
3. Task Dashboard
Display total tasks, pending tasks, completed tasks, and tasks currently in progress.
4. User Authentication
Implement registration and login functionality using JWT authentication so different users can manage their own tasks.
5. Search Functionality
Allow users to search tasks by title, description, or category.
6. Pagination
Display tasks in smaller groups instead of loading all records simultaneously. This is useful when the database contains thousands of tasks.
15. Security Best Practices
Security is an important part of every backend application.
While developing a Task Manager using Node.js and MongoDB, consider the following practices:
1. Validate user input
Always validate incoming data before saving it to MongoDB. Check required fields, data types, valid ObjectIds, and allowed values.
2. Protect database credentials
Store MongoDB credentials in environment variables. Never expose database passwords in source code.
3. Implement authentication
Use JWT-based authentication to verify users before allowing access to private task operations.
4. Apply authorization
Users should only be able to view, update, or delete their own tasks. Authentication alone does not provide ownership protection.
5. Use secure HTTP headers
Consider using Helmet to configure appropriate security-related HTTP headers.
npm install helmet
Then configure it:
const helmet = require("helmet");
app.use(helmet());
6. Apply rate limiting
Use rate limiting to reduce excessive API requests and help protect the application against abuse.
7. Handle errors properly
Avoid exposing internal stack traces, database credentials, or sensitive server information in API responses.
These practices help make the application more reliable and suitable for future production development.
16. Common Challenges and Their Solutions
During development, you may encounter some common problems.
| Problem | Possible solution |
|---|---|
| MongoDB connection failed | Verify MongoDB service and connection string |
| Category not found | Verify that the category ObjectId exists |
| Invalid ObjectId | Validate IDs before database queries |
| Duplicate category | Handle MongoDB duplicate-key errors |
| Task not updating | Check the request body and validation rules |
| API returns empty results | Verify filters and database records |
| Slow queries | Analyze execution plans and create suitable indexes |
Understanding these errors is useful because debugging is an important part of real-world backend development.
17. What Have We Learned From This Project?
By building this Task Manager application, we have explored several important backend development concepts.
| Concept | What you learned |
|---|---|
| Node.js | Server-side JavaScript development |
| Express.js | REST API creation |
| MongoDB | Document-based data storage |
| Mongoose | Schema design and database operations |
| CRUD | Create, Read, Update, Delete |
| ObjectId Reference | Relationships between collections |
| Populate | Retrieving referenced documents |
| Filtering | Retrieving specific records |
| Indexing | Improving database query performance |
| Postman | Testing backend APIs |
These concepts are useful when developing larger applications such as project management systems, employee management platforms, CRM applications, and inventory management systems.
18. Conclusion
Building a Simple Task Manager With Categories Using Node.js and MongoDB is an excellent practical project for understanding backend development.
Throughout this tutorial, we created a backend application that supports task creation, category management, task updates, deletion, filtering, and database integration.
We also explored MongoDB schema design, Mongoose relationships, REST APIs, and indexing techniques.
The biggest takeaway is that even a small application can teach important software development concepts when it is designed with proper architecture and database structure.
If you are learning backend development, don’t stop with basic CRUD operations. Try implementing authentication, pagination, dashboard analytics, and task reminders to make your application more powerful.
Want to build real-world backend development skills?
At Learnomate Technologies, we focus on practical, industry-oriented technical learning that helps learners understand concepts through hands-on projects and real-world scenarios.
Explore Learnomate to strengthen your technical knowledge and develop skills that can help you grow in the IT industry.
-
Website: https://learnomate.org/

