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 …
Section overview
5 resourcesCovers 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
- 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
- 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}`);
});
- 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
- 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);
-
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);
- 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
-
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!
- 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);
- 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);
- 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.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI 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 articleAI 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 articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article