Most web applications need to store data persistently. In this lesson, you will learn how to connect an Express application to both SQL and NoSQL databases and perform create, read, update, and delete (CRUD) operations.
Choosing a Database
| Type | Examples | Best For |
|---|---|---|
| SQL | PostgreSQL, MySQL | Structured data, complex queries, relationships |
| NoSQL | MongoDB, Redis | Flexible schemas, rapid prototyping |
| In-memory | Redis, SQLite | Caching, sessions, quick prototypes |
For production applications, PostgreSQL is an excellent default choice. MongoDB is popular for projects where schema flexibility matters.
SQLite for Development
SQLite is a file-based database perfect for development and prototyping. Install the better-sqlite3 driver:
npm install better-sqlite3Integrating with Express
Create a data access layer that your routes can use:
MongoDB with Mongoose
For NoSQL, MongoDB with Mongoose is a popular combination:
npm install mongooseConnecting
Defining a Schema
CRUD with Mongoose
Database Transactions
Transactions ensure that multiple operations either all succeed or all fail:
Database Migrations
As your schema evolves, use migrations to track changes:
For production, use a migration tool like knex, prisma migrate, or sequelize-cli.
Practical Exercise
Build a complete bookstore API with database integration:
Key Takeaways
- Choose SQL for structured data with relationships; choose NoSQL for flexible schemas.
- SQLite is excellent for development and prototyping — no server setup required.
- Always validate input before writing to the database and handle constraint errors gracefully.
- Use transactions when multiple operations must succeed or fail together.
- Separate your database logic from your route handlers for cleaner, testable code.