Database Integration

Express doesn't care which database you use. However, there are established best practices for organizing your database logic.

1. The Model Directory

Always separate your database schemas and logic from your route handlers.

// models/User.js
      const mongoose = require('mongoose');
      const userSchema = new mongoose.Schema({ ... });
      module.exports = mongoose.model('User', userSchema);

2. Decoupled Connection

Connect to the database before starting the Express server.

const mongoose = require('mongoose');
      const app = require('./app');

      mongoose.connect(process.env.DB_URI)
        .then(() => {
          app.listen(3000, () => console.log('DB Connected & Server Running'));
        });

3. Using Controllers

In a large Express app, use Controllers to handle the interaction between Routes and Models.

// controllers/userController.js
      exports.getAllUsers = async (req, res) => {
        const users = await User.find();
        res.json(users);
      };

4. Relational vs NoSQL

  • Sequelize (SQL): Great for Postgre, MySql with complex relations.
  • Mongoose (NoSQL): Perfect for MongoDB and flexible data models.
  • Prisma: A modern Type-safe approach for both SQL and NoSQL.
Tip: Use express-async-errors or a custom catchAsyncutility to avoid wrapping every database call in a try/catch block.