Express.js / Express.js and MongoDB

Connecting Express.js to MongoDB

This tutorial will guide you through the process of connecting an Express.js application to a MongoDB database. You'll learn how to use Mongoose to facilitate this connection and …

Tutorial 1 of 5 5 resources in this section

Section overview

5 resources

Covers integrating Express.js with MongoDB for data storage and retrieval.

Introduction

This tutorial aims to show you how to connect an Express.js application to a MongoDB database using the Mongoose library. We'll cover setting up a connection, designing a simple schema, and performing basic Create, Read, Update, and Delete (CRUD) operations.

By the end of this tutorial, you will be able to:

  • Set up a MongoDB database connection in your Express.js app using Mongoose
  • Define a Mongoose schema and model
  • Perform basic CRUD operations on MongoDB documents

Prerequisites

Before starting, you should have basic knowledge of JavaScript, Node.js, and Express.js. You should also have Node.js and MongoDB installed in your system.

Step-by-Step Guide

  1. Install the necessary packages

Before we begin, we need to install Express.js and Mongoose. In your terminal, navigate to your project directory and run:

npm init -y
npm install express mongoose
  1. Set up your Express.js app

Create a new file named app.js in your project root and add the following:

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

app.listen(port, () => {
  console.log(`App running on port ${port}`);
});
  1. Connect your app to MongoDB

Still in app.js, import Mongoose and connect to your MongoDB database:

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/my_database', { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => console.log('Connected to MongoDB'))
  .catch(err => console.error('Could not connect to MongoDB...', err));

Code Examples

  1. Defining a schema and model

Let's create a simple Mongoose schema and model. In this example, we'll design a schema for a "Book":

const bookSchema = new mongoose.Schema({
  title: String,
  author: String,
  published_year: Number
});

const Book = mongoose.model('Book', bookSchema);
  1. Performing CRUD operations

  2. Creating a book

const book = new Book({
  title: 'My New Book',
  author: 'John Doe',
  published_year: 2021
});

const result = await book.save();
console.log(result);
  • Reading a book
const books = await Book.find();
console.log(books);
  • Updating a book
const result = await Book.updateOne({ _id: id }, {
  $set: {
    title: 'Updated Title'
  }
});
console.log(result);
  • Deleting a book
const result = await Book.deleteOne({ _id: id });
console.log(result);

Summary

In this tutorial, we've learned how to connect an Express.js app to MongoDB using Mongoose. We've also learned how to perform basic CRUD operations.

For further learning, practice more CRUD operations and explore Mongoose validation, middleware, and other advanced features.

Practice Exercises

  1. Create a new Mongoose model "Author" with fields "name", "biography", "date_of_birth". Save a new author in the database.

  2. Create a new "Publisher" model with fields "name", "location". Then, update the "Book" model to include references to the "Author" and "Publisher" models.

  3. Implement a route in your Express app for fetching all books from the database.

Here are the solutions, but try to complete the exercises on your own before checking!

  1. Solution
const authorSchema = new mongoose.Schema({
  name: String,
  biography: String,
  date_of_birth: Date
});

const Author = mongoose.model('Author', authorSchema);

const author = new Author({
  name: 'John Doe',
  biography: 'An amazing author',
  date_of_birth: '1990-01-01'
});

const result = await author.save();
console.log(result);
  1. Solution
const publisherSchema = new mongoose.Schema({
  name: String,
  location: String
});

const Publisher = mongoose.model('Publisher', publisherSchema);

const bookSchema = new mongoose.Schema({
  title: String,
  author: { type: mongoose.Schema.Types.ObjectId, ref: 'Author' },
  publisher: { type: mongoose.Schema.Types.ObjectId, ref: 'Publisher' },
  published_year: Number
});

const Book = mongoose.model('Book', bookSchema);
  1. Solution
app.get('/books', async (req, res) => {
  const books = await Book.find();
  res.send(books);
});

Keep practicing and exploring the Mongoose API for further mastery. 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

QR Code Generator

Generate QR codes for URLs, text, or contact info.

Use tool

PDF Password Protector

Add or remove passwords from PDF files.

Use tool

Meta Tag Analyzer

Analyze and generate meta tags for SEO.

Use tool

EXIF Data Viewer/Remover

View and remove metadata from image files.

Use tool

CSV to JSON Converter

Convert CSV files to JSON format and vice versa.

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