MongoDB / MongoDB with Node.js and Express

Building a REST API with Express and MongoDB

This tutorial will guide you through the process of designing and building a RESTful API using Express.js and MongoDB. The API will handle HTTP requests and interact with the Mong…

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Explains integrating MongoDB with Node.js and Express for web applications.

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!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Base64 Encoder/Decoder

Encode and decode Base64 strings.

Use tool

AES Encryption/Decryption

Encrypt and decrypt text using AES encryption.

Use tool

File Size Checker

Check the size of uploaded files.

Use tool

Word to PDF Converter

Easily convert Word documents to PDFs.

Use tool

Random String Generator

Generate random alphanumeric strings for API keys or unique IDs.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help