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:
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.
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
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}`);
});
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));
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);
Performing CRUD operations
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);
const books = await Book.find();
console.log(books);
const result = await Book.updateOne({ _id: id }, {
$set: {
title: 'Updated Title'
}
});
console.log(result);
const result = await Book.deleteOne({ _id: id });
console.log(result);
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.
Create a new Mongoose model "Author" with fields "name", "biography", "date_of_birth". Save a new author in the database.
Create a new "Publisher" model with fields "name", "location". Then, update the "Book" model to include references to the "Author" and "Publisher" models.
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!
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);
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);
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!