- Express.js Basics
- Express.js HOME
- Express.js Introduction
- Express.js Installation
- Express.js Basic App
- Express.js Routing
- Basics Routing
- Route Parameters
- Handling Query Strings
- Router Middleware
- Middleware
- What is Middleware?
- Application-Level Middleware
- Router-Level Middleware
- Built-In Middleware
- Error-Handling Middleware
- Third-Party Middleware
- Express.js HTTP
- Handling GET Requests
- Handling POST Requests
- Handling PUT Requests
- Handling DELETE Requests
- Templating Engines
- Using Templating Engines
- Setting Up EJS
- Setting Up Handlebars
- Setting Up Pug
- Request/Response
- Request Object
- Response Object
- Handling JSON Data
- Handling Form Data
- Static Files
- Serving Static Files
- Setting Up Static Folders
- Managing Assets
- Express.js Advanced
- Middleware Stack
- CORS in Express.js
- JWT Authentication
- Session Handling
- File Uploads
- Error Handling
- Databases
- Express.js with MongoDB
- MongoDB CRUD Operations
- Express.js with MySQL
- MySQL CRUD Operations
- Deployment
- Deploying Express.js Apps to Heroku
- Deploying Express.js Apps to AWS
- Deploying Express.js Apps to Vercel
Express.js with MongoDB
Integrating MongoDB with Express.js enables developers to build dynamic, data-driven web applications. MongoDB serves as a NoSQL database, and its flexibility complements the lightweight nature of Express.js.
Key Features of Express.js with MongoDB
- Scalable Database Integration: MongoDB's schema-less design allows for flexible data storage.
- RESTful APIs: Seamless creation of APIs to interact with the database.
- Asynchronous Operations: Leverage asynchronous operations for efficient data processing.
- Full-Stack Capabilities: Combine with front-end frameworks for end-to-end solutions.
Setting Up MongoDB with Express.js
Install Required Packages
Install mongodb
or mongoose
for database interactions.
Example:
npm install mongoose
Connect to MongoDB
Establish a connection using Mongoose.
Example:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.error('Connection failed', err));
Define a Schema and Model
Create a schema for your data and define a model.
Example:
const userSchema = new mongoose.Schema({
name: String,
email: String,
age: Number
});
const User = mongoose.model('User', userSchema);
Create API Endpoints
Use Express.js routes to interact with the database.
Insert Data:
app.post('/add-user', async (req, res) => {
const user = new User(req.body);
try {
await user.save();
res.send('User added successfully');
} catch (err) {
res.status(400).send(err.message);
}
});
Fetch Data:
app.get('/users', async (req, res) => {
try {
const users = await User.find();
res.json(users);
} catch (err) {
res.status(500).send(err.message);
}
});
Update Data:
app.put('/update-user/:id', async (req, res) => {
try {
const user = await User.findByIdAndUpdate(req.params.id, req.body, { new: true });
res.json(user);
} catch (err) {
res.status(400).send(err.message);
}
});
Delete Data:
app.delete('/delete-user/:id', async (req, res) => {
try {
await User.findByIdAndDelete(req.params.id);
res.send('User deleted successfully');
} catch (err) {
res.status(500).send(err.message);
}
});
Complete Example
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
// MongoDB connection
mongoose.connect('mongodb://localhost:27017/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true });
// Schema and model
const userSchema = new mongoose.Schema({
name: String,
email: String,
age: Number
});
const User = mongoose.model('User', userSchema);
// Routes
app.post('/add-user', async (req, res) => {
const user = new User(req.body);
try {
await user.save();
res.send('User added successfully');
} catch (err) {
res.status(400).send(err.message);
}
});
app.get('/users', async (req, res) => {
try {
const users = await User.find();
res.json(users);
} catch (err) {
res.status(500).send(err.message);
}
});
// Server
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Summary
Express.js and MongoDB work seamlessly to handle database-driven applications. By using Mongoose or MongoDB's native driver, developers can efficiently manage CRUD operations, enabling robust back-end development.