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
- var express = require('express')
- var mongoose = require('mongoose')
- var path = require('path')
- var bodyParser = require('body-parser')
- var userRoutes = require('./routes/users')
-
-
-
-
- mongoose.connect('mongodb://localhost:27017/demoDB',{useNewUrlParser:true})
- .then(()=>console.log('connected to database')).catch(error=>console.log('error occured',error))
-
-
- var app = express()
-
-
- app.set("views",path.resolve(__dirname,'views'))
-
-
- app.set('view engine','ejs')
-
-
- app.use(bodyParser.urlencoded({extended:false}))
-
-
-
- app.use('/user/',userRoutes);
-
-
- var port = process.env.port || 3000;
-
-
- app.listen(port,()=>console.log(`server running at port ${port}`))
-
- module.exports = app;
Model
- var mongoose = require('mongoose')
-
-
- var userSchema = new mongoose.Schema({
- firstname : String,
- lastname : String,
- city : String,
- state : String,
- country : String
- })
-
-
-
- var userModel = module.exports = mongoose.model('user',userSchema)
-
-
-
- module.exports.getUser=(cb)=>{
- userModel.find((err,data)=>{
- if(err){
- console.log(err)
- }
- else{
- cb(null,data)
- }
- })
- }
-
-
-
- module.exports.addUser=(newUser,cb)=>{
- const user = new userModel({
- firstname:newUser.firstname,
- lastname:newUser.lastname,
- city:newUser.city,
- state:newUser.state,
- country:newUser.country
- })
- user.save(cb)
- }
Routes
- var express = require('express');
- var userControler = require('../controller/userController');
-
-
-
- var router = express.Router();
-
-
-
- router.get('/home',userControler.userHome)
-
-
-
- router.post('/add',userControler.addUsers)
-
- module.exports = router;
Controller
-
- var userModel = require('../models/user');
-
-
- var usersController={
- userHome(req,res){
-
- userModel.getUser((err,data)=>{
- try {
- if(err){
- console.log(err)
- }
- else if(data){
- res.render('home',{data:data})
- }
- else{
- res.render('home',{data:{}})
- }
- } catch (error) {
- console.log(error)
- }
- })
- },
- addUsers(req,res){
- try {
- console.log('adduser',req.body)
- const user = {
- firstname:req.body.firstname,
- lastname:req.body.lastname,
- city:req.body.city,
- state:req.body.state,
- country:req.body.country
- };
-
-
- userModel.addUser(user,(err,data)=>{
- if(err){
- console.log('error occured',err)
- }
- else{
- console.log(data)
- res.redirect('/user/home')
- }
- })
- }
- catch (error) {
- console.log('error',error)
- }
- }
-
- }
-
- module.exports = usersController;
Views
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta http-equiv="X-UA-Compatible" content="ie=edge">
- <title>Document</title>
- </head>
- <body>
- <h4>AddNewUser</h4>
- <form action="/user/add" method="POST" >
- <table>
-
- <tr>
- <td>
- <input type="text" name="firstname" placeholder="firstname">
- </td>
- <td>
- <input type="text" name="lastname" placeholder="lastname">
- </td>
- <td>
- <input type="text" name="city" placeholder="city">
- </td>
- <td>
- <input type="text" name="state" placeholder="state">
- </td>
- <td>
- <input type="text" name="country" placeholder="country">
- </td>
- <td>
- <input type="submit" value="add"><br>
- </td>
-
- </tr>
-
- </table>
- </form>
- <br>
- <% if (data.length > 0) {%>
- <h2>AllUser</h2>
- <table border="1" style="text-align: center;font-family: 'Courier New', Courier, monospace;font: 600;">
- <thead>
- <tr>
- <th>
- firstname
- </th>
- <th>
- lastname
- </th>
- <th>
- city
- </th>
- <th>
- state
- </th>
- <th>
- country
- </th>
- </tr>
- </thead>
- <tbody>
- <% for(var i=0; i < data.length; i++) {%>
- <tr>
- <td><%= data[i].firstname%></td>
- <td><%= data[i].lastname%></td>
- <td><%= data[i].city%></td>
- <td><%= data[i].state%></td>
- <td><%= data[i].country%></td>
- </tr>
- <% } %>
- </tbody>
- </table>
- <% } %>
- </body>
- </html>