Lesson 18 / 25
Express + a Database
Connect Express to MongoDB with Mongoose or to SQL databases with a driver, opening the connection once at startup.
No database built in
Express has no opinion on storage. For MongoDB, apps commonly use Mongoose (an ODM); for PostgreSQL/MySQL, the pg driver or an ORM like Prisma.
A minimal Mongoose route
Connect once at startup, then use a model inside route handlers.
import mongoose from 'mongoose';
await mongoose.connect(process.env.MONGO_URI);
const User = mongoose.model('User', new mongoose.Schema({
name: String,
email: String,
}));
app.get('/users', async (req, res, next) => {
try {
const users = await User.find();
res.json(users);
} catch (err) {
next(err);
}
});Quick check: What is Mongoose?
- A CSS framework
- A replacement for Express itself
- A template engine
- An ODM for modeling MongoDB data in Node
Answer
An ODM for modeling MongoDB data in Node — Mongoose is an Object Data Modeling library that sits on top of the MongoDB driver.