CLI Task Manager
Now that you''ve learned all about MongoDB and how to use it with Node.js, it''s time to build something real! In this project, we''ll build a command-line task manager that stores tasks in MongoDB. You''ll be able to add, list, complete, and delete tasks ā all from your terminal.
Project Overview: Task Manager CLI
Our task manager will be a command-line tool that lets users:
- Add a new task (with title and description)
- List all tasks (show title, status, and ID)
- Mark a task as complete
- Delete a task
This project will use Mongoose for database operations, and we''ll parse command-line arguments to handle different commands. It''s a perfect real-world example of MongoDB in action!
Step 1: Project Setup
mkdir task-manager-clicd task-manager-clinpm init -ynpm install mongoose dotenvStep 2: Environment Variables
Create a `.env` file:
MONGODB_URI=mongodb://localhost:27017/task-managerStep 3: Create the Task Model
Create `models/Task.js`:
const mongoose = require('mongoose');
const taskSchema = new mongoose.Schema({ title: { type: String, required: [true, 'Task title is required'], trim: true }, description: { type: String, trim: true }, completed: { type: Boolean, default: false }, createdAt: { type: Date, default: Date.now }});
module.exports = mongoose.model('Task', taskSchema);Step 4: Database Connection
Create `db.js`:
require('dotenv').config();const mongoose = require('mongoose');
const connectDB = async () => { try { await mongoose.connect(process.env.MONGODB_URI); console.log('Connected to MongoDB'); } catch (err) { console.error('Database connection error:', err); process.exit(1); }};
module.exports = connectDB;Step 5: Main Application (app.js)
require('dotenv').config();const connectDB = require('./db');const Task = require('./models/Task');
<!-- Get command and arguments -->const command = process.argv[2];const args = process.argv.slice(3);
<!-- Helper to display tasks -->function displayTask(task) { const status = task.completed ? : ; console.log(`${status} [${task._id}] ${task.title}`); if (task.description) { console.log(` Description: ${task.description}`); }}
<!-- Main function -->async function run() { await connectDB(); switch (command) { case 'add': await addTask(); break; case 'list': await listTasks(); break; case 'complete': await completeTask(); break; case 'delete': await deleteTask(); break; default: console.log('Usage: node app.js [arguments]' ); console.log('Commands:'); console.log(' add "title" "description" - Add a new task'); console.log(' list - List all tasks'); console.log(' complete - Mark task as complete' ); console.log(' delete - Delete a task' ); process.exit(1); } <!-- Close MongoDB connection --> await mongoose.connection.close(); process.exit(0);}
<!-- Add Task Function -->async function addTask() { if (args.length < 1) { console.log('Please provide a task title'); return; } const title = args[0]; const description = args[1] || ''; try { const task = new Task({ title, description }); await task.save(); console.log('Task added successfully!'); displayTask(task); } catch (err) { console.error('Error adding task:', err.message); }}
<!-- List Tasks Function -->async function listTasks() { try { const tasks = await Task.find().sort({ createdAt: -1 }); if (tasks.length === 0) { console.log('No tasks found.'); return; } console.log('nš Your Tasks:n'); tasks.forEach(task => displayTask(task)); } catch (err) { console.error('Error listing tasks:', err); }}
<!-- Complete Task Function -->async function completeTask() { if (args.length === 0) { console.log('Please provide a task ID'); return; } const taskId = args[0]; try { const task = await Task.findByIdAndUpdate( taskId, { completed: true }, { new: true } ); if (!task) { console.log('Task not found'); return; } console.log('Task marked as complete!'); displayTask(task); } catch (err) { console.error('Error completing task:', err.message); }}
<!-- Delete Task Function -->async function deleteTask() { if (args.length === 0) { console.log('Please provide a task ID'); return; } const taskId = args[0]; try { const task = await Task.findByIdAndDelete(taskId); if (!task) { console.log('Task not found'); return; } console.log('Task deleted successfully!'); } catch (err) { console.error('Error deleting task:', err.message); }}
<!-- Start the app -->run();Two Minute Drill
- We built a complete CLI task manager using MongoDB and Mongoose.
- Used `process.argv` to parse command-line arguments.
- Created a Task model with title, description, and completed status.
- Implemented add, list, complete, and delete functionality.
- Used `findByIdAndUpdate()` and `findByIdAndDelete()` for operations.
- Always close database connection after operations.
Need more clarification?
Drop us an email at career@quipoinfotech.com
