Building a REST API with Express and MongoDB

Tutorial 3 of 5

Introduction

This tutorial aims to guide you through the process of creating a RESTful API using Express.js and MongoDB. A RESTful API is an application program interface (API) that uses HTTP methods like GET, POST, PUT, DELETE to manage data. Express.js is a fast, unopinionated, and minimalist web framework for Node.js, while MongoDB is a source-available cross-platform document-oriented database program.

By the end of this tutorial, you will be able to:
1. Set up an Express.js application.
2. Create a MongoDB database and connect it with Express.js.
3. Build a RESTful API that interacts with the MongoDB database.

Prerequisites:
- Basic knowledge of JavaScript and Node.js.
- Node.js and NPM installed on your system.
- Postman for testing our API endpoints.
- MongoDB installed on your machine or MongoDB Atlas account for cloud-based MongoDB service.

Step-by-Step Guide

Step 1: Setting Up Your Project

Create a new directory for your project, navigate into it and initialize a new Node.js project by running the following commands:

mkdir express-mongodb-api
cd express-mongodb-api
npm init -y

Install Express.js and MongoDB driver for Node.js:

npm install express mongodb

Step 2: Setting Up Express.js

Create a new file app.js and require express module:

const express = require('express');
const app = express();

app.get('/', (req, res) => {
    res.send('Hello World!');
});

app.listen(3000, () => console.log('Server started on port 3000'));

Start your server by running node app.js.

Step 3: Connecting to MongoDB

You can connect to MongoDB using the mongodb package. Make sure to replace <your-db-url> with your actual MongoDB URL.

const MongoClient = require('mongodb').MongoClient;
const url = "<your-db-url>";
let db;

MongoClient.connect(url, { useUnifiedTopology: true }, (err, client) => {
  if (err) throw err;
  db = client.db("<your-db-name>");
  console.log("Database created!");
});

Step 4: Creating API Endpoints

You can create API endpoints to perform CRUD operations on MongoDB:

app.get('/users', (req, res) => {
  // Fetch all users from the database
  db.collection('users').find().toArray((err, result) => {
    if (err) throw err;
    res.send(result);
  });
});

app.post('/users', (req, res) => {
  // Add new user to the database
});

app.put('/users/:id', (req, res) => {
  // Update a user in the database
});

app.delete('/users/:id', (req, res) => {
  // Delete a user from the database
});

Note: Express.js doesn't parse JSON in the body of the request by default. You need to add app.use(express.json()) before your API endpoints.

Code Examples

Let's add some data to our MongoDB database. We'll use Postman to make requests to our API.

Code for adding a new user:

app.post('/users', (req, res) => {
  db.collection('users').insertOne(req.body, (err, result) => {
    if (err) throw err;
    res.send('User added successfully');
  });
});

In Postman, make a POST request to http://localhost:3000/users with body:

{
  "name": "John Doe",
  "email": "john@example.com"
}

Code for updating a user:

app.put('/users/:id', (req, res) => {
  let query = { _id: ObjectId(req.params.id) };
  let newValues = { $set: req.body };

  db.collection('users').updateOne(query, newValues, (err, result) => {
    if (err) throw err;
    res.send('User updated successfully');
  });
});

Summary

In this tutorial, we've learned how to set up an Express.js application, create a MongoDB database and connect it with Express.js, and build a RESTful API that interacts with the MongoDB database.

For further learning, you can explore more about MongoDb operations, middleware in Express.js, and data validation.

Practice Exercises

  1. Create a new endpoint to fetch a single user from the database.
  2. Add error handling to your API endpoints.
  3. Add data validation before inserting or updating a user in the database.

Remember, practice is key when learning web development. Happy coding!