In this tutorial, we will walk you through the process of creating a REST API using Node.js and Express. We will also utilize MongoDB as our database to store the data.

Introduction

Our goal is to develop a trip cost calculator app. Imagine you are going on a trip and want to keep track of your expenses, such as gasoline, hotels, food, tickets, etc. You want to have an app where you can add and archive each expense, allowing you to review your spending history. While we won’t cover the frontend development in this tutorial, we will focus on creating the API.

API Endpoints Overview

Let’s start by defining the endpoints for our API:

  1. /trip with the POST method: This endpoint will create a new trip with a specified name.

  2. /trips with the GET method: This endpoint will list all the trips, ordered by creation date.

  3. /expense with the POST method: This endpoint will add a new expense to a specific trip.

  4. /expenses with the GET method: This endpoint will retrieve all the expenses for a specific trip.

Setting up the Project

To begin, make sure you have Node.js installed on your system. Create a new folder for your project called “tripcost” and navigate to that folder in your terminal. Initialize the project using the command npm init -y.

We’ll also need to install two packages: mongodb and express. Run the following command to install both packages:

npm install mongodb express

Next, create a new file called server.js and import the necessary modules:

const express = require("express");
const mongo = require("mongodb").MongoClient;

const app = express();

Implementing the API Endpoints

Now, let’s add the stubs for the API endpoints:

app.post("/trip", (req, res) => {
  // Implement creating a new trip
});

app.get("/trips", (req, res) => {
  // Implement retrieving the list of trips
});

app.post("/expense", (req, res) => {
  // Implement adding a new expense
});

app.get("/expenses", (req, res) => {
  // Implement retrieving the list of expenses for a trip
});

Finally, start the server using the listen() method:

app.listen(3000, () => console.log("Server ready"));

Adding a Trip

Let’s start by implementing the /trip endpoint for creating a new trip:

app.post("/trip", (req, res) => {
  const name = req.body.name;

  // Implement inserting the new trip into the database
});

First, we need to establish a connection to the MongoDB database. Add the following code before the /trip endpoint implementation:

let db, trips, expenses;

const url = "mongodb://localhost:27017";

mongo.connect(
  url,
  {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  },
  (err, client) => {
    if (err) {
      console.error(err);
      return;
    }
    db = client.db("tripcost");
    trips = db.collection("trips");
    expenses = db.collection("expenses");
  }
);

Now, we can continue with the implementation of the /trip endpoint:

app.post("/trip", (req, res) => {
  const name = req.body.name;

  trips.insertOne({ name: name }, (err, result) => {
    if (err) {
      console.error(err);
      res.status(500).json({ err: err });
      return;
    }
    res.status(200).json({ ok: true });
  });
});

Listing Trips

Next, we’ll implement the /trips endpoint to retrieve the list of trips:

app.get("/trips", (req, res) => {
  trips.find().toArray((err, items) => {
    if (err) {
      console.error(err);
      res.status(500).json({ err: err });
      return;
    }
    res.status(200).json({ trips: items });
  });
});

Adding an Expense

Let’s move on to implementing the /expense endpoint for adding a new expense:

app.post("/expense", (req, res) => {
  expenses.insertOne(
    {
      trip: req.body.trip,
      date: req.body.date,
      amount: req.body.amount,
      category: req.body.category,
      description: req.body.description,
    },
    (err, result) => {
      if (err) {
        console.error(err);
        res.status(500).json({ err: err });
        return;
      }
      res.status(200).json({ ok: true });
    }
  );
});

Listing Expenses

Lastly, let’s implement the /expenses endpoint to retrieve the list of expenses for a specific trip:

app.get("/expenses", (req, res) => {
  expenses.find({ trip: req.body.trip }).toArray((err, items) => {
    if (err) {
      console.error(err);
      res.status(500).json({ err: err });
      return;
    }
    res.status(200).json({ expenses: items });
  });
});

Conclusion

Congratulations! You have successfully built a REST API using Node.js, Express, and MongoDB. Now, you can create, retrieve, and manage trips and expenses in your app. Feel free to explore and expand upon this foundation to further develop your application.

Tags: Node.js, Express, MongoDB, REST API