Understanding MVC Architecture: Beginner Tutorial with Node.js

Model-View-Controller (MVC) is a popular software design pattern that separates an application into three interconnected components: the Model, the View, and the Controller.

This pattern has been widely adopted by developers across various programming languages, including JavaScript, which is used in Node.js. In this article, we will explore how to use MVC in Node.js to create scalable and maintainable web applications.

What is MVC?

Before diving into MVC in Node.js, let’s first understand what MVC is and why it is important. MVC is a software design pattern that helps developers organize code by separating concerns into three distinct components: Model, View, and Controller. Each component has a specific role:

  • Model: The model represents the data and the business logic of the application. It handles data storage, retrieval, and manipulation, and interacts with the database or external APIs.
  • View: The view represents the user interface of the application. It handles the presentation of data to the user and receives input from the user.
  • Controller: The controller acts as the mediator between the model and the view. It receives input from the user via the view, interacts with the model to retrieve or manipulate data, and updates the view accordingly.

By separating concerns into these three components, developers can create applications that are easier to maintain, scale, and test. MVC also encourages code reusability, which can lead to faster development cycles and more efficient use of resources.

MVC in Node.js

Node.js is a popular server-side JavaScript runtime that allows developers to build scalable and high-performance applications. With Node.js, developers can use MVC to create web applications that are both efficient and maintainable.

To implement MVC in Node.js, we need to use a framework that supports this pattern. One such framework is Express.js, which is a minimal and flexible web application framework that provides a set of tools for building HTTP servers and handling HTTP requests.

Let’s take a look at how we can use MVC with Express.js to create a simple web application.

Model

The first component of MVC is the Model, which represents the data and the business logic of the application. In our example, we will create a simple model that stores a list of books.

const books = [
  { id: 1, title: "The Great Gatsby", author: "F. Scott Fitzgerald" },
  { id: 2, title: "To Kill a Mockingbird", author: "Harper Lee" },
  { id: 3, title: "1984", author: "George Orwell" },
];

In a real-life situation, we probably wouldn’t want to model our data with plain JSON like this. We would most certainly use a database, such as MongoDB, but it’s not required for the sake of this tutorial.

View

The second component of MVC is the View, which represents the user interface of the application. In our example, we will create a simple view that displays a list of books from the array above.

<!DOCTYPE html>
<html>
  <head>
    <title>Books</title>
  </head>
  <body>
    <h1>Books</h1>
    <ul>
      <% books.forEach(function(book) { %>
      <li><%= book.title %> by <%= book.author %></li>
      <% }) %>
    </ul>
  </body>
</html>

This weird looking syntax is coming from EJS, a JavaScript templating engine.

Controller

The third and final component of MVC is the Controller, which acts as the mediator between the model and the view. In our example, we will create a simple controller that retrieves the list of books from the model and passes it to the view for rendering.

const express = require("express");
const ejs = require("ejs");
const app = express();

// Setting the view
app.set("view engine", "ejs");
app.set("views", __dirname + "/views");

// Controller
app.get("/", function (req, res) {
  res.render("books", { books });
});

app.listen(3000, function () {
  console.log("Server is listening on port 3000");
});

In the code, we are using the Express.js framework to create a server and define a single route that responds to GET requests on the root path ("/"). When a user visits the root path, the controller retrieves the list of books from the model and passes it to the view for rendering. Again, we are using the EJS templating engine to render the view.

Full code

const express = require("express");
const app = express();
const ejs = require("ejs");

// Model
const books = [
  { id: 1, title: "The Great Gatsby", author: "F. Scott Fitzgerald" },
  { id: 2, title: "To Kill a Mockingbird", author: "Harper Lee" },
  { id: 3, title: "1984", author: "George Orwell" },
];

// View
app.set("view engine", "ejs");
app.set("views", __dirname + "/views");

// Controller
app.get("/", (req, res) => {
  res.render("books", { books });
});

// Server
const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server is listening on port ${PORT}`);
});

Note: You will need to create the file structure for this file.

  • Create a directory, mvc
  • Run npm init -y
  • Add a file, index.js
  • Add a folder, views and include a books.ejs file in this folder (which will contain the HTML code from above)
  • Run npm i ejs express
  • Run node index.js, then navigate to localhost:3000 in your browser

Now, the example isn’t really all that impressive. But it shows you enough of the MVC pattern so that you can understand it. Feel free to style it and create something with the basic outline above.

Conclusion

MVC is a powerful software design pattern that can help developers create maintainable and scalable web applications. In Node.js, we can use the Express.js framework to implement MVC and create web applications that are both efficient and maintainable.

By separating concerns into three distinct components, we can create applications that are easier to test, debug, and maintain. With the popularity of Node.js continuing to grow, it’s important for developers to have a solid understanding of MVC and how to implement it in their projects.

FAQ

Q: What is MVC?

A: MVC is a software architectural pattern that separates an application’s data (the model), user interface (the view), and control logic (the controller) into separate components.

Q: What are the benefits of using MVC?

A: The benefits of using MVC include improved modularity, maintainability, and scalability of the application’s code. It also makes it easier to modify or extend the application’s functionality.

Q: What are the components of MVC?

A: The components of MVC are the model, the view, and the controller. The model represents the application’s data and business logic, the view represents the user interface, and the controller acts as an intermediary between the model and the view, handling user input and updating the model and view accordingly.

Q: What programming languages are commonly used with MVC?

A: MVC can be used with a variety of programming languages, but it is commonly used with languages such as Java, Node.js, C#, and Ruby on Rails.

Q: How does MVC differ from other software architectural patterns?

A: MVC differs from other software architectural patterns in that it separates the application’s data, user interface, and control logic into separate components, whereas other patterns may combine some or all of these components in different ways.

Q: Are there any downsides to using MVC?

A: One potential downside of using MVC is that it may increase the complexity of the application’s code, especially for small or simple applications. Additionally, implementing MVC correctly can require a significant amount of upfront design and planning.

Note: These are affiliate links. We will earn a (very) small commission if you buy these products from the links above. Thanks for the support!

comments powered by Disqus

Related Posts

Finding Free and Discounted Programming Books

As an avid reader, I’m always looking for places to find my next book. If they’re free, even better. Although it’s not always so easy finding them, there are plenty available online.

Read more

Getting Started with Google Cloud

In this article, we’re going to be taking a first look at Google Cloud, a leading player in the world of cloud computing, offers services and tools designed to drive innovation and ease operations.

Read more

The Great JavaScript Debate: To Semicolon or Not?

Since I’ve started learning this language, JavaScript has undergone some heavy changes. Most notably, it seems to be the norm to not use semicolons anymore.

Read more