Video Tutorial
What is the MVC?
MVC stands for Model, View, Controller is an architectural pattern that separates an application into three main logical components: the model, the view, and the controller. Each one of these components is built to handle specific development aspects of an application.
MVC is architecture used in building Web Servers that focus on reliability and making the development process much simpler and easier since it composes the Web Server into three separate parts.
Controller is the part that takes care of client request processing which handles the HTTP Request and returns a response the response could be either a JSON if you’re calling an API endpoint or regular HTML webpage.
Model is the database interface which lets you interact with the database API and create different entity schemas of your app on the database (MySQL, MongoDB), it gets called from controller depending on the client’s request if it needs a stored data then the controller will ask the model interface for providing it with the needed data.
View is what compiles and renders into plain HTML and what the client in most cases going to get back as a response of what he requested (for ex: to view his profile details), the view needs to use a Template Engine for doing the rendering process where the controller feed it with needed data (data from database and client) and the view renders and convert everything into plain HTML that the browser could understand and display.
So the three different components interact with each other perfectly to ensure reliable and flexible client request processing, either for simple tasks like accessing the home page or updating his profile data, that’s why building your Web Server around and MVC Architecture is really cool and will let you with tons of options and flexible thoughts.
You may also wanna take a closer look on the Diagram I made for the video to explain the MVC architecture and how it works with a client.
Create an MVC Express App
Now let’s try to make things clear about why using an MVC is useful and how it can turn your standard Express/Node.js App into a high-level app just by wrapping around an MVC Architecture.
You can clone the basic Express App we will try to work on from this Github Repo.
The repository contains a very basic Node.js/Express app that has only one route for the home page and some pug (Template Engine) templates, let’s try to create a very simple Restaurant Menu (Meals) App.
Now, since the Architecture is composed of three main parts (Controller, Model and View) so under the src/ folder go and create a new subfolder for each MVC part.
src/
--controllers/
--models/
--views/
--routes/
boostrap.js
Also, make sure to create a routes folder for holding all the routes that our app going to have, since a controller must be linked with route to listen for a specific HTTP request that comes across this route, and a bootstrap.js file that will do the job of starting the application and liking all the three components together.
The app.js module on the root folder is the main server start point has the setup for a minimal Express Server with Body parser and a simple home page route handler.
Creating a Simple Model
Models are an interface between the controller and the actual database API which you will need in order to save data, update or fetch so first we need to create a model for the meals menu of the restaurant.
We are not going to use a real database, so, we will be implementing all the data inside the javascript file on an array just to make things clear, you would use the same thing when dealing with a database system (ex: MongoDB).
//Keep the meals data inside of an Array (in Real World this would be saved in a database)
const meals = [
{ name: "MilkShake", type: "breakfast", price: 8 },
{ name: "Lazanya", type: "lunch", price: 20 }
];
//Allow the Controller to access and fetch the meals meanu
exports.getMeals = () => {
return meals;
};
We put all the meals data inside of an array, in a real-world scenario this would be saved on a real database system then we export a function that will allow the controller to fetch the meals menu of the restaurant.
This is simply what a model is, handles the database part and makes data available to the user.
App Routes
Routes are constraints that decide when a controller should run, (if the request if for the controller’s path) so we have each controller with its route.
Create an index.js file inside the routes/ folder that will be the default require file whenever we import the routes subfolder.
//Get Meals MENU Controller
mealsController = require("../controllers/mealsController");
//Function will be called from bootstrap (that will get the router and link routes with controllers)
exports.appRoute = router => {
// /menu path is for getting the meals menu
router.get("/menu", mealsController.getMenuController);
};
Then you have to call the appRoute function on the bootstrap module and pass it the router to make sure it does the linking process of routes with their specified controllers.
Creating Menu Controller
The Controller is the crucial part on an MVC pattern it is the part that does the request handling data fetching from the database through the model if needed and responding back to the client with a compiled view, and on Express controllers are type of a callback that gets request, response and next objects passed in as arguments.
First, create a new controller inside the controllers/ subfolder name it mealsController that will do the handling for the meals menu of the restaurant.
//Import Meals Model for database data
const mealModel = require("../models/mealModel");
//menu controller takes the request, response and next object
exports.getMenuController = (req, res, next) => {
//Get menu meals from model (Array)
const meals = mealModel.getMeals();
//Show JSON object of Meals Menu data
res.json(meals);
};
We still need to link it with the bootstrap module that will link everything together.
/* bootstrap.js */
route = require("./routes");
//Default function that will bootstrap the routes and link it with controllers
module.exports = (app, router) => {
//Initialize Routes
route.appRoute(router);
};
And finally, make sure to call the bootstrap on the main server starting script (app.js) and pass it the app instance and the router.
/* app.js */
...
const bootstrap = require("./src/boostrap");
bootstrap(app, router);
...
And you MVC pattern wrapped App is finished and now you can run the server and navigate on your browser to the (localhost:3000/menu) you should be able to see the JSON list of Meals Data, Awesome!
Using Views (Pug)
Mostly, you do not want to only show the user with JSON data unless you are creating an API in that case you need to use a view, and you have to create it using a specific template engine (we will using Pug).
For the view, we need to render each meal on the list by feeding the template with the meals menu array and then on the template we loop through each item on the array and show it.
Create a menu.pug file under the views/ folder and make sure to tell Express that you are using Pug and of course you need to change the default views directory into yours (/src/views).
//Use a Custom Templating Engine
app.set("view engine", "pug");
//Change views default directory
app.set("views", path.resolve("./src/views"));
Now let’s create our template that will render the Restaurant Meals Menu.
html
body
ul
each meal in meals
li #{meal.name} price: #{meal.price}
The Above template is written on Pug so if you are not familiar with it, you can Watch this full tutorial to learn everything about Pug Template Engine.
The last thing is to render the menu.pug on controller response instead of responding back with a JSON object.
/* mealsController.js */
...
const meals = mealModel.getMeals();
//Pass it the meals array to render (that's how you feed data into views)
res.render("menu", { meals });
...
Now you can navigate again to the localhost server /menu and you should see an HTML page displayed on your browser.
What’s Next
Now you have got a basic idea of how an MVC application works and why it makes development super easy and simple, especially when the project grows and gets more code, algorithm, packages it depends on so you still have control over your app and easily be able to maintain it.
You can take this simple Restaurant application and create a much more advanced one with cool features, don’t forget to share it with us!