DEV Community

Dev.Faanid
Dev.Faanid

Posted on

Building a Simple Task Management API with Node.js, Express and MongoDB

Introdoction

Task management is a crucial aspect of many applications and building a robust backend to handle tasks can streamline your development process. In this article, we'll create a simple Task Management API using Node.js, Express, and MongoDB. The code is organized into three main files: server.js, connectDB.js, and taskModel.js.

1. Setting up the Express Server

Let's start by setting up our Express server in server.js. This file acts as the entry point for our application.

// server.js

const dotenv = require("dotenv").config();
const express = require("express");
const connectDB = require("./config/connectDB");
const mongoose = require("mongoose");
const Task = require("./model/taskModel");

const app = express();

// Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

// Routes
app.get("/", (req, res) => {
  res.send("Home page");
});

// Create a Task
app.post("/api/tasks", async (req, res) => {
  try {
    const task = await Task.create(req.body);
    res.json(task);
  } catch (error) {
    res.status(500).json({ msg: error.message });
  }
});

const PORT = process.env.PORT || 5000;

const startServer = async () => {
  try {
    await connectDB();
    app.listen(PORT, () => {
      console.log(`Server running on port ${PORT}`);
    });
  } catch (error) {
    console.log(error);
  }
};

startServer();

Enter fullscreen mode Exit fullscreen mode

In this code snippet, we've set up an Express server, defined a simple route for the home page, and created an API endpoint for adding tasks.

2. Connecting to MongoDB

The connectDB.js file is responsible for establishing a connection to our MongoDB database using Mongoose.

// connectDB.js

const mongoose = require("mongoose");

const connectDB = async () => {
  try {
    const connect = await mongoose.connect(process.env.MONGO_URI);
    console.log(`MongoDB Connected`);
  } catch (error) {
    console.log(error);
    process.exit(1);
  }
};

module.exports = connectDB;

Enter fullscreen mode Exit fullscreen mode

This module exports a function that connects to MongoDB using the URI specified in the MONGO_URI environment variable.

3. Creating the Task Model

In taskModel.js, we define the Mongoose schema for our tasks and create a model based on that schema.


// taskModel.js

const mongoose = require("mongoose");

const taskSchema = mongoose.Schema(
  {
    name: {
      type: String,
      required: [true, "Please add a task"],
    },
    completed: {
      type: Boolean,
      required: true,
      default: false,
    },
  },
  {
    timestamps: true,
  }
);

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

module.exports = Task;

Enter fullscreen mode Exit fullscreen mode

This module exports the Task model, which represents the structure of our task documents in the MongoDB collection.

Adding more features
updating and
deleting tasks,
implementing,
user authentication...

Top comments (0)