Express.js MVC Pattern

MVC stands for Model, View, and Controller. It is a design pattern that splits an app into three parts with clear duties. The model handles data. The view shows the result to the user. The controller connects the two. Express does not demand MVC, yet most professional Express apps follow it because it keeps code tidy.

Think of a restaurant again. The pantry stores ingredients, which is the model. The plated dish on the table is the view. The chef takes the order, collects ingredients, and plates the dish, which is the controller.

The Three Parts

Model

The model defines the shape of data and talks to the database. It knows nothing about URLs or screens. A User model might hold fields for name and email and offer methods to find or save users.

View

The view builds what the user sees. In a web page app, a template engine such as EJS or Pug renders HTML. In a JSON API, the view is simply the JSON response.

Controller

The controller receives the request, asks the model for data, and picks the view or JSON reply. Each controller function handles one action, such as listing books or adding a book.

MVC Diagram

            +-----------+
 Request -> |   Route   |
            +-----------+
                  |
                  v
            +-----------+
            | Controller|
            +-----------+
             |         |
     asks data         sends result
             |         |
             v         v
       +---------+  +--------+
       |  Model  |  |  View  |
       +---------+  +--------+
             |
             v
         Database

Folder Layout

library-app/
|-- models/
|   |-- bookModel.js
|-- views/
|   |-- books.ejs
|-- controllers/
|   |-- bookController.js
|-- routes/
|   |-- bookRoutes.js
|-- app.js

Build a Book List With MVC

Model: models/bookModel.js

const books = [
  { id: 1, title: 'Clean Code', author: 'Robert Martin' },
  { id: 2, title: 'You Do Not Know JS', author: 'Kyle Simpson' }
];

exports.getAll = () => books;

exports.getById = (id) => books.find((b) => b.id === id);

exports.add = (title, author) => {
  const book = { id: books.length + 1, title, author };
  books.push(book);
  return book;
};

This model keeps data in a simple array. A real app swaps the array for Mongoose or SQL calls, and the controller stays unchanged.

Controller: controllers/bookController.js

const Book = require('../models/bookModel');

exports.listBooks = (req, res) => {
  const books = Book.getAll();
  res.render('books', { books });
};

exports.showBook = (req, res) => {
  const book = Book.getById(Number(req.params.id));
  if (!book) return res.status(404).send('Book not found');
  res.json(book);
};

exports.createBook = (req, res) => {
  const { title, author } = req.body;
  const book = Book.add(title, author);
  res.status(201).json(book);
};

View: views/books.ejs

<h1>Library Books</h1>
<ul>
  <% books.forEach(function(book) { %>
    <li><%= book.title %> by <%= book.author %></li>
  <% }); %>
</ul>

Route: routes/bookRoutes.js

const express = require('express');
const router = express.Router();
const controller = require('../controllers/bookController');

router.get('/', controller.listBooks);
router.get('/:id', controller.showBook);
router.post('/', controller.createBook);

module.exports = router;

App: app.js

const express = require('express');
const app = express();

app.set('view engine', 'ejs');
app.use(express.json());
app.use('/books', require('./routes/bookRoutes'));

app.listen(3000);

Benefits of MVC

  • Developers change the database without touching the screens.
  • Designers change the screens without touching the data code.
  • Teams work in parallel on separate layers.
  • Tests target one layer with simple inputs.

Rules That Keep MVC Clean

  1. Keep database code out of controllers.
  2. Keep request and response objects out of models.
  3. Keep logic out of views. Views only display values.
  4. Keep routes thin. A route only names the controller function.

An API without HTML pages still benefits from the pattern. The JSON reply plays the role of the view, and the model and controller keep their jobs.

Real-World Scenario

A growing online store starts with ten routes and ends with two hundred. The team keeps one controller per resource, such as products, orders, and customers. A new developer opens the orders controller and finds every order action in one place. A change to the payment database touches only the model files, and the rest of the store keeps working.