How To Setup MVC Design Pattern In Express

Introduction

I assume that you should be a little familiar with the technologies express, mongoose, and ejs. If you are not, then click below to read about them.
What is MVC?

Model–View–Controller (usually known as MVC) is a software design pattern commonly used for developing user interfaces which divides the related program logic into three interconnected elements. Now this pattern has become popular for designing web applications too. The MVC is based on three components.

Model

  • This is the central component of the pattern.
  • It directly manages the data, logic, and rules of the application.
  • It receives user input from the controller.
View
  • The View component is used for all the UI logic of the application.
  • It presents the model’s data to the user.
  • Basically it just receives the data from the model and displays it to the user.  
Controller
  • In between model and view, we have the controller. 
  • It processes all the business logic and incoming requests and manipulates data using Model.
  • It renders the final output file interacting with views.
Setting up a node project. 
  • Open console/terminal make a new folder using mkdir which is followed by the folder name.
  • Change to the new folder using cd followed by folder name.
  • Now setup node in project using npm init -y.
  • This will generate a package.json file in the project which will tell that node is initialized in the project.
  • Now install basic packages using npm install which will be followed by package names.
  • express,body-parser ,mongoose, and ejs are the packages we will install.
Setup MVC pattern in project
  • After installing the packages, make a few new folders: a) models b) views c) controller d) routes.

  • Models folder will contain the entire collection which will be used in our project.
  • Views folder will contain pages that will contain a mix of HTML and model data.
  • The controller folder will contain the business logic which will be executed on the request.
  • Routes will contain the routes of the application.
 
 
App.js
  1. var express  = require('express')  
  2. var mongoose = require('mongoose')  
  3. var path     = require('path')  
  4. var bodyParser = require('body-parser')  
  5. var userRoutes = require('./routes/users')  
  6.   
  7.   
  8. //connecting to database  
  9. //demoDB is the name of database  
  10. mongoose.connect('mongodb://localhost:27017/demoDB',{useNewUrlParser:true})  
  11. .then(()=>console.log('connected to database')).catch(error=>console.log('error occured',error))  
  12.   
  13. //initializing the object instance  
  14. var app = express()  
  15.   
  16. //setting the path of our views folder  
  17. app.set("views",path.resolve(__dirname,'views'))  
  18.   
  19. //setting the template engine  
  20. app.set('view engine','ejs')  
  21.   
  22. //fetch form data from the request  
  23. app.use(bodyParser.urlencoded({extended:false}))  
  24.   
  25. //the request having /user/ will be send to the userRoutes module.  
  26. //in that the rquest will be directed to the specific route.   
  27. app.use('/user/',userRoutes);  
  28.   
  29. //setting the port for the server.  
  30. var port = process.env.port || 3000;  
  31.   
  32. //showing the port on which server is running  
  33. app.listen(port,()=>console.log(`server running at port ${port}`))  
  34.   
  35. module.exports = app;  
Model
  • user.js 
  1. var mongoose  = require('mongoose')  
  2.   
  3. //specify the fields which we want in our collection(table).  
  4. var userSchema = new mongoose.Schema({  
  5.     firstname : String,  
  6.     lastname  : String,  
  7.     city      : String,  
  8.     state     : String,  
  9.     country   : String  
  10.  })  
  11.   
  12.  //here we saving our collectionSchema with the name user in database  
  13.  //userModel will contain the instance of the user for manipulating the data.  
  14.  var userModel = module.exports = mongoose.model('user',userSchema)  
  15.   
  16. //this function will find all the user   
  17. //there will be just a callback parameter  
  18. module.exports.getUser=(cb)=>{  
  19.     userModel.find((err,data)=>{  
  20.         if(err){  
  21.             console.log(err)  
  22.         }  
  23.         else{  
  24.             cb(null,data)  
  25.         }  
  26.     })  
  27. }  
  28.   
  29. //this will add new user to the user collection  
  30. //this will take 2 parameter.newUser is object and cb is a callback  
  31. module.exports.addUser=(newUser,cb)=>{  
  32.       const user = new userModel({  
  33.           firstname:newUser.firstname,  
  34.           lastname:newUser.lastname,  
  35.           city:newUser.city,  
  36.           state:newUser.state,  
  37.           country:newUser.country   
  38.       })  
  39.       user.save(cb)  
  40.  }  
Routes
  • users.js
  1. var express =  require('express');  
  2. var userControler = require('../controller/userController');  
  3.   
  4. // express.Router is a class to create route handlers  
  5. //router will contain the Router instance.  
  6. var router = express.Router();  
  7.   
  8. //this route will be executed on /user/home request  
  9. //userHome function will be called from the controller when request come for this route.  
  10.  router.get('/home',userControler.userHome)  
  11.   
  12. //this route will be executed on /user/add  
  13. //addUsers function will be called from the controller when request come for this route.  
  14.  router.post('/add',userControler.addUsers)  
  15.   
  16. module.exports = router;  
Controller 
  • userController.js
  1. //contain instance of user model  
  2. var userModel = require('../models/user');  
  3.   
  4. //containt the function with business logics  
  5. var usersController={  
  6.        userHome(req,res){  
  7.            //this will call the getuser function present in user.js   
  8.            userModel.getUser((err,data)=>{  
  9.                try {  
  10.                  if(err){  
  11.                     console.log(err)  
  12.                  }     
  13.                  else if(data){  
  14.                    res.render('home',{data:data})  
  15.                  }  
  16.                  else{  
  17.                      res.render('home',{data:{}})  
  18.                  }  
  19.                } catch (error) {  
  20.                 console.log(error)  
  21.                }  
  22.            })  
  23.     },  
  24.      addUsers(req,res){  
  25.          try {  
  26.          console.log('adduser',req.body)  
  27.         const user = {  
  28.             firstname:req.body.firstname,  
  29.             lastname:req.body.lastname,  
  30.             city:req.body.city,  
  31.             state:req.body.state,  
  32.             country:req.body.country  
  33.         };   
  34.            //this will call the adduser function present in user.js.  
  35.            //it will take object as parameter.   
  36.        userModel.addUser(user,(err,data)=>{  
  37.            if(err){  
  38.                console.log('error occured',err)  
  39.            }  
  40.            else{  
  41.                console.log(data)  
  42.              res.redirect('/user/home')  
  43.            }  
  44.        })  
  45.     }  
  46.         catch (error) {  
  47.                  console.log('error',error)      
  48.         }  
  49.  }  
  50.   
  51. }  
  52.   
  53. module.exports = usersController;  
Views
  • home.ejs
  1.  <html lang="en">  
  2.  <head>  
  3.      <meta charset="UTF-8">  
  4.      <meta name="viewport" content="width=device-width, initial-scale=1.0">  
  5.      <meta http-equiv="X-UA-Compatible" content="ie=edge">  
  6.      <title>Document</title>  
  7.  </head>  
  8.  <body>  
  9.         <h4>AddNewUser</h4>  
  10.         <form action="/user/add" method="POST" >  
  11.      <table>  
  12.          
  13.             <tr>  
  14.                 <td>  
  15.                         <input type="text" name="firstname" placeholder="firstname">  
  16.                 </td>  
  17.                 <td>  
  18.                         <input type="text" name="lastname" placeholder="lastname">  
  19.                 </td>  
  20.                 <td>  
  21.                         <input type="text" name="city" placeholder="city">  
  22.                 </td>  
  23.                 <td>  
  24.                         <input type="text" name="state" placeholder="state">  
  25.                 </td>  
  26.                  <td>  
  27.                         <input type="text" name="country" placeholder="country">  
  28.                  </td>  
  29.                  <td>  
  30.                         <input type="submit" value="add"><br>  
  31.                  </td>  
  32.   
  33.             </tr>  
  34.         
  35.     </table>  
  36. </form>  
  37.     <br>  
  38.     <% if (data.length > 0) {%>  
  39.     <h2>AllUser</h2>  
  40.     <table border="1" style="text-align: center;font-family: 'Courier New', Courier, monospace;font: 600;">  
  41.         <thead>  
  42.             <tr>  
  43.                 <th>  
  44.                     firstname  
  45.                 </th>  
  46.                 <th>  
  47.                     lastname  
  48.                 </th>  
  49.                 <th>  
  50.                     city  
  51.                 </th>  
  52.                 <th>  
  53.                     state  
  54.                 </th>  
  55.                 <th>  
  56.                     country  
  57.                 </th>  
  58.             </tr>  
  59.         </thead>  
  60.         <tbody>  
  61.             <% for(var i=0; i < data.length; i++) {%>  
  62.             <tr>  
  63.              <td><%= data[i].firstname%></td>  
  64.              <td><%= data[i].lastname%></td>  
  65.              <td><%= data[i].city%></td>  
  66.              <td><%= data[i].state%></td>  
  67.              <td><%= data[i].country%></td>  
  68.             </tr>  
  69.             <% } %>  
  70.         </tbody>  
  71.     </table>  
  72.     <% } %>  
  73.  </body>  
  74.  </html>