Simple Task Management Application

Simple Task Management Application

Simple Task Management Application

This guide walks you through building a basic Task Management Application using Node.js, Express.js, MongoDB, and Mongoose. It will allow users to create, retrieve, update, and delete tasks β€” commonly known as CRUD operations.

Features

  • Create a new task
  • Get a list of all tasks
  • Update a task
  • Delete a task

Step 1: Project Setup

mkdir task-manager
cd task-manager
npm init -y
npm install express mongoose dotenv

Step 2: Basic Folder Structure

Organize your project files as follows:

task-manager/
β”œβ”€β”€ config/
β”‚   └── database.js
β”œβ”€β”€ models/
β”‚   └── Task.js
β”œβ”€β”€ routes/
β”‚   └── tasks.js
β”œβ”€β”€ .env
β”œβ”€β”€ app.js
β”œβ”€β”€ package.json

Step 3: MongoDB Connection

config/database.js

const mongoose = require('mongoose');

const connectDB = async () => {
    try {
        await mongoose.connect(process.env.MONGO_URI, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
        });
        console.log('MongoDB Connected');
    } catch (err) {
        console.error(err.message);
        process.exit(1);
    }
};

module.exports = connectDB;

Step 4: Create Task Model

models/Task.js

const mongoose = require('mongoose');

const TaskSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    completed: {
        type: Boolean,
        default: false
    },
    createdAt: {
        type: Date,
        default: Date.now
    }
});

module.exports = mongoose.model('Task', TaskSchema);

Step 5: Define Routes

routes/tasks.js

const express = require('express');
const router = express.Router();
const Task = require('../models/Task');

// Get all tasks
router.get('/', async (req, res) => {
    try {
        const tasks = await Task.find();
        res.json(tasks);
    } catch (err) {
        res.status(500).json({ message: err.message });
    }
});

// Create new task
router.post('/', async (req, res) => {
    const task = new Task({
        title: req.body.title,
    });

    try {
        const newTask = await task.save();
        res.status(201).json(newTask);
    } catch (err) {
        res.status(400).json({ message: err.message });
    }
});

// Update task
router.put('/:id', async (req, res) => {
    try {
        const task = await Task.findById(req.params.id);
        if (!task) return res.status(404).json({ message: 'Task not found' });

        task.title = req.body.title || task.title;
        task.completed = req.body.completed !== undefined ? req.body.completed : task.completed;

        const updatedTask = await task.save();
        res.json(updatedTask);
    } catch (err) {
        res.status(400).json({ message: err.message });
    }
});

// Delete task
router.delete('/:id', async (req, res) => {
    try {
        const task = await Task.findById(req.params.id);
        if (!task) return res.status(404).json({ message: 'Task not found' });

        await task.deleteOne();
        res.json({ message: 'Task deleted' });
    } catch (err) {
        res.status(500).json({ message: err.message });
    }
});

module.exports = router;

Step 6: App Entry Point

app.js

const express = require('express');
const dotenv = require('dotenv');
const connectDB = require('./config/database');
const taskRoutes = require('./routes/tasks');

dotenv.config();
connectDB();

const app = express();
app.use(express.json());

app.use('/api/tasks', taskRoutes);

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

Step 7: Create .env File

MONGO_URI=mongodb://localhost:27017/taskdb
PORT=5000

Step 8: Running the Application

Make sure MongoDB is running on your system, then run the app:

node app.js

Use Postman or any API testing tool to perform CRUD operations:

  • GET http://localhost:5000/api/tasks
  • POST http://localhost:5000/api/tasks with JSON body {"title": "Buy groceries"}
  • PUT http://localhost:5000/api/tasks/:id with JSON body {"completed": true}
  • DELETEhttp://localhost:5000/api/tasks/:id

You've now built a complete and functional Task Management REST API using Node.js, Express, and MongoDB with Mongoose. You can now expand this project by adding features like user authentication, due dates, task categories, or a frontend with React or Vue.js.

Beginner 5 Hours
Simple Task Management Application

Simple Task Management Application

This guide walks you through building a basic Task Management Application using Node.js, Express.js, MongoDB, and Mongoose. It will allow users to create, retrieve, update, and delete tasks — commonly known as CRUD operations.

Features

  • Create a new task
  • Get a list of all tasks
  • Update a task
  • Delete a task

Step 1: Project Setup

mkdir task-manager cd task-manager npm init -y npm install express mongoose dotenv

Step 2: Basic Folder Structure

Organize your project files as follows:

task-manager/ ├── config/ │ └── database.js ├── models/ │ └── Task.js ├── routes/ │ └── tasks.js ├── .env ├── app.js ├── package.json

Step 3: MongoDB Connection

config/database.js

const mongoose = require('mongoose'); const connectDB = async () => { try { await mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true, }); console.log('MongoDB Connected'); } catch (err) { console.error(err.message); process.exit(1); } }; module.exports = connectDB;

Step 4: Create Task Model

models/Task.js

const mongoose = require('mongoose'); const TaskSchema = new mongoose.Schema({ title: { type: String, required: true }, completed: { type: Boolean, default: false }, createdAt: { type: Date, default: Date.now } }); module.exports = mongoose.model('Task', TaskSchema);

Step 5: Define Routes

routes/tasks.js

const express = require('express'); const router = express.Router(); const Task = require('../models/Task'); // Get all tasks router.get('/', async (req, res) => { try { const tasks = await Task.find(); res.json(tasks); } catch (err) { res.status(500).json({ message: err.message }); } }); // Create new task router.post('/', async (req, res) => { const task = new Task({ title: req.body.title, }); try { const newTask = await task.save(); res.status(201).json(newTask); } catch (err) { res.status(400).json({ message: err.message }); } }); // Update task router.put('/:id', async (req, res) => { try { const task = await Task.findById(req.params.id); if (!task) return res.status(404).json({ message: 'Task not found' }); task.title = req.body.title || task.title; task.completed = req.body.completed !== undefined ? req.body.completed : task.completed; const updatedTask = await task.save(); res.json(updatedTask); } catch (err) { res.status(400).json({ message: err.message }); } }); // Delete task router.delete('/:id', async (req, res) => { try { const task = await Task.findById(req.params.id); if (!task) return res.status(404).json({ message: 'Task not found' }); await task.deleteOne(); res.json({ message: 'Task deleted' }); } catch (err) { res.status(500).json({ message: err.message }); } }); module.exports = router;

Step 6: App Entry Point

app.js

const express = require('express'); const dotenv = require('dotenv'); const connectDB = require('./config/database'); const taskRoutes = require('./routes/tasks'); dotenv.config(); connectDB(); const app = express(); app.use(express.json()); app.use('/api/tasks', taskRoutes); const PORT = process.env.PORT || 5000; app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

Step 7: Create .env File

MONGO_URI=mongodb://localhost:27017/taskdb PORT=5000

Step 8: Running the Application

Make sure MongoDB is running on your system, then run the app:

node app.js

Use Postman or any API testing tool to perform CRUD operations:

  • GET http://localhost:5000/api/tasks
  • POST http://localhost:5000/api/tasks with JSON body {"title": "Buy groceries"}
  • PUT http://localhost:5000/api/tasks/:id with JSON body {"completed": true}
  • DELETEhttp://localhost:5000/api/tasks/:id

You've now built a complete and functional Task Management REST API using Node.js, Express, and MongoDB with Mongoose. You can now expand this project by adding features like user authentication, due dates, task categories, or a frontend with React or Vue.js.

Related Tutorials

Frequently Asked Questions for Node.js

A function passed as an argument and executed later.

Runs multiple instances to utilize multi-core systems.

Reusable blocks of code, exported and imported using require() or import.

nextTick() executes before setImmediate() in the event loop.

Starts a server and listens on specified port.

Node Package Manager β€” installs, manages, and shares JavaScript packages.

A minimal and flexible web application framework for Node.js.

A stream handles reading or writing data continuously.

It processes asynchronous callbacks and non-blocking I/O operations efficiently.

Node.js is a JavaScript runtime built on Chrome's V8 engine for server-side scripting.

An object representing the eventual completion or failure of an asynchronous operation.

require is CommonJS; import is ES6 syntax (requires transpilation or newer versions).

Use module.exports or exports.functionName.

Variables stored outside the code for configuration, accessed using process.env.


MongoDB, often used with Mongoose for schema management.

Describes project details and manages dependencies and scripts.

Synchronous blocks execution; asynchronous runs in background without blocking.

Allows or restricts resources shared between different origins.

Use try-catch, error events, or middleware for error handling.

Provides file system-related operations like read, write, delete.

Using event-driven architecture and non-blocking I/O.

Functions in Express that execute during request-response cycle.

A set of routes or endpoints to interact with server logic or databases.

Yes, it's single-threaded but handles concurrency using the event loop and asynchronous callbacks.

Middleware to parse incoming request bodies, like JSON or form data.

line

Copyrights © 2024 letsupdateskills All rights reserved