MongoDB - Getting StartedMongoDB - Getting Started1

Project 1: Task Tracker with Node.js + MongoDB



Project 1: Task Tracker with Node.js + MongoDB

In this project, you'll build a basic task tracker using Node.js and MongoDB. This real-world app helps you understand how to connect to a MongoDB database, design a schema, and implement CRUD operations in a Node.js environment.

What We'll Build

A minimal task manager that lets users:

Step 1: Initialize the Project

Create a new directory and initialize a Node.js project:


    mkdir task-tracker
    cd task-tracker
    npm init -y
    

Install the required packages:


    npm install express mongoose body-parser nodemon
    

Step 2: Create Project Structure

Set up your file structure like this:

    task-tracker/
    ├── models/
    │   └── Task.js
    ├── routes/
    │   └── tasks.js
    ├── server.js
    

Step 3: Connect to MongoDB

Edit server.js to set up Express and connect to MongoDB:


// server.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const taskRoutes = require('./routes/tasks');

const app = express();
app.use(bodyParser.json());
app.use('/api/tasks', taskRoutes);

mongoose.connect('mongodb://localhost:27017/taskdb', {
  useNewUrlParser: true,
  useUnifiedTopology: true
}).then(() => {
  console.log('Connected to MongoDB');
  app.listen(3000, () => console.log('Server running on port 3000'));
}).catch(err => console.error(err));
    

Output:

    Connected to MongoDB
    Server running on port 3000
    

Step 4: Define the Task Model

Create the file models/Task.js:


// models/Task.js
const mongoose = require('mongoose');

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

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

Q: Why use a schema if MongoDB is schema-less?

A: While MongoDB itself is flexible, using Mongoose schemas helps enforce structure and validation within our application logic.

Step 5: Create the Task Routes

Create routes/tasks.js to define all task-related routes:


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

// Add new task
router.post('/', async (req, res) => {
  try {
    const task = new Task({ title: req.body.title });
    await task.save();
    res.status(201).json(task);
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});

// Get all tasks
router.get('/', async (req, res) => {
  const tasks = await Task.find();
  res.json(tasks);
});

// Update task (mark as complete)
router.put('/:id', async (req, res) => {
  try {
    const task = await Task.findByIdAndUpdate(
      req.params.id,
      { completed: true },
      { new: true }
    );
    res.json(task);
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});

// Delete task
router.delete('/:id', async (req, res) => {
  try {
    await Task.findByIdAndDelete(req.params.id);
    res.json({ message: 'Task deleted' });
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});

module.exports = router;
    

Step 6: Run and Test the API

Start the server with nodemon:


    npx nodemon server.js
    

Use Postman or cURL to test the endpoints:

POST /api/tasks — Add a task


    curl -X POST http://localhost:3000/api/tasks -H "Content-Type: application/json" -d '{"meta_title": "Learn MongoDB"}'
    

Output:

    {
      "_id": "664218c0a83dfb31c5ebd511",
      "meta_title": "Learn MongoDB",
      "completed": false,
      "__v": 0
    }
    

GET /api/tasks — Get all tasks


    curl http://localhost:3000/api/tasks
    

PUT /api/tasks/:id — Mark task as completed

DELETE /api/tasks/:id — Delete a task

Conclusion

You've successfully created a full CRUD application using Node.js and MongoDB. This task tracker taught you how to structure a backend app, use Mongoose for schema modeling, and interact with a database through API endpoints.

In the next project, we'll expand this knowledge by building a blog platform using Express and MongoDB with advanced features like user management and pagination.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

Mention your name, and programguru.org in the message. Your name shall be displayed in the sponsers list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M