Connecting Express.js to MongoDB

Tutorial 1 of 5

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!