Integrating Express.js with MongoDB
1. Introduction
This lesson covers the integration of Express.js, a minimal and flexible Node.js web application framework, with MongoDB, a NoSQL database. By the end of this lesson, you’ll learn how to set up a basic Express application, connect it to a MongoDB database, and perform CRUD (Create, Read, Update, Delete) operations.
2. Prerequisites
Before proceeding, ensure you have the following installed:
- Node.js (v12 or later)
- NPM (Node Package Manager)
- MongoDB (installed locally or use MongoDB Atlas)
- Basic understanding of JavaScript and Node.js
3. Setup
Follow these steps to set up your Express.js application and connect it to MongoDB:
-
Create a new directory for your project:
mkdir express-mongo-demo
-
Navigate into the directory:
cd express-mongo-demo
-
Initialize a new Node.js project:
npm init -y
-
Install Express and Mongoose:
npm install express mongoose
-
Create an entry point file:
touch index.js
4. Basic CRUD Operations
Now that your setup is complete, let’s implement basic CRUD operations. Use the following code in index.js
:
const express = require('express');
const mongoose = require('mongoose');
const app = express();
app.use(express.json()); // Middleware to parse JSON
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('MongoDB connected'))
.catch(err => console.error('MongoDB connection error:', err));
// Define a simple Mongoose schema
const ItemSchema = new mongoose.Schema({
name: String,
});
const Item = mongoose.model('Item', ItemSchema);
// Create an item
app.post('/items', async (req, res) => {
const item = new Item(req.body);
await item.save();
res.status(201).send(item);
});
// Read items
app.get('/items', async (req, res) => {
const items = await Item.find();
res.send(items);
});
// Update an item
app.put('/items/:id', async (req, res) => {
const item = await Item.findByIdAndUpdate(req.params.id, req.body, { new: true });
res.send(item);
});
// Delete an item
app.delete('/items/:id', async (req, res) => {
await Item.findByIdAndDelete(req.params.id);
res.status(204).send();
});
// Start the server
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
This code sets up an Express server that connects to a MongoDB database and provides endpoints for creating, reading, updating, and deleting items.
5. Best Practices
- Always validate user input to prevent injection attacks.
- Use environment variables to store sensitive information (e.g., database URIs).
- Implement error handling middleware for centralized error management.
- Structure your code for scalability (consider MVC architecture).
6. FAQ
What is Mongoose?
Mongoose is an ODM (Object Data Modeling) library for MongoDB and Node.js, providing a schema-based solution to model application data.
How do I connect to a remote MongoDB database?
Replace the local MongoDB URI with your remote database URI in the mongoose.connect()
method.
What are the advantages of using MongoDB?
MongoDB offers flexible schema design, scalability, and ease of use for handling large volumes of unstructured data.