Expert IT Solutions

Discover New Ideas and Solutions with CodeEssence Blogs

Get inspired with our insightful blog posts covering innovative solutions, ideas, and strategies to elevate your business.

shape image
shape image
shape image
shape image
shape image
shape image
shape image
image

Building a Scalable Task Scheduler with Node.js and MongoDB

In today's fast-paced world, task scheduling applications play a crucial role in managing time effectively. Whether it's scheduling reminders, events, or automated tasks, having a reliable system can save time and improve productivity. In this blog, we will build a scalable task scheduler using Node.js and MongoDB from scratch. This application will allow users to create, update, and delete scheduled tasks.

Let's get started by setting up our project environment.

Step 1: Setting Up the Project

First, ensure that you have Node.js and MongoDB installed on your machine. Then follow these steps:

  1. Create a new directory for your project:
Bash
mkdir task-scheduler
cd task-scheduler
  1. Initialize a new Node.js project:
Bash
npm init -y
  1. Install the necessary packages:
Bash
npm install express mongoose body-parser

Step 2: Setting Up the Server

Next, let's set up the server using Express:

Javascript
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');

const app = express();
const PORT = process.env.PORT || 3000;

app.use(bodyParser.json());

// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/taskScheduler', {
    useNewUrlParser: true,
    useUnifiedTopology: true
}).then(() => {
    console.log('MongoDB connected successfully');
}).catch(err => console.log(err));

app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

Step 3: Creating the Task Model

Let's create a model for our tasks:

Javascript
const taskSchema = new mongoose.Schema({
    title: { type: String, required: true },
    description: { type: String, required: false },
    dueDate: { type: Date, required: true },
    completed: { type: Boolean, default: false }
});

const Task = mongoose.model('Task', taskSchema);

Step 4: Creating RESTful API Endpoints

Now, we will create endpoints to handle task operations:

Javascript
// Create a new task
app.post('/tasks', async (req, res) => {
    const newTask = new Task(req.body);
    try {
        const savedTask = await newTask.save();
        res.status(201).json(savedTask);
    } catch (err) {
        res.status(500).json(err);
    }
});

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

// Update a task
app.put('/tasks/:id', async (req, res) => {
    try {
        const updatedTask = await Task.findByIdAndUpdate(req.params.id, req.body, { new: true });
        res.status(200).json(updatedTask);
    } catch (err) {
        res.status(500).json(err);
    }
});

// Delete a task
app.delete('/tasks/:id', async (req, res) => {
    try {
        await Task.findByIdAndDelete(req.params.id);
        res.status(204).send();
    } catch (err) {
        res.status(500).json(err);
    }
});

Step 5: Testing the API

With our API endpoints ready, we can use Postman or any other API testing tool to test our application. Make sure MongoDB is running and then start your server:

Bash
node app.js

Now you can create, read, update, and delete tasks by sending appropriate requests to the defined endpoints.

Conclusion

In this guide, we built a simple yet scalable task scheduler using Node.js and MongoDB. You can expand this application by adding user authentication, task reminders, or even a front-end using React or Flutter. Happy coding!

0 Comments:

Leave a Reply

Your email address will not be published. Required fields are marked *

Author *

Comment *