Building a Simple CRUD App with NodeJS

CRUD, Express, and MongoDB are big words for a person who has never touched any server-side programming in their life. Building a Simple CRUD App with NodeJS.

Build a school management from scratch using MongoDB & Express.We are not using Reactjs for the front-end. We will use handlebars (hbs) template engine.

MongoDB, Express and Nodejs are often used with familiar powerful frontend frameworks such as Angular or React to make an open source software development stack (or technology) for modern JavaScript developers. These stacks are called MEAN and MERN respectively.

Express is a framework for building web applications on top of Node.js.

Now this is our CRUD Project in Nodejs with MongoDB.

The below images shows our MongoDB database design . Just make start Mongo compass for database activity.

Below is our Package.json file. So please Install all required dependency by using npm. npm install mongoose , npm install multer , npm install nodemon . The multer is used for file Image and Mongoose is for MongoDB.

{
  "name": "admint_card",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon index.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "express": "^4.17.1",
    "express-handlebars": "^5.2.0",
    "file": "^0.2.2",
    "fs": "0.0.1-security",
    "hbs": "^4.1.1",
    "mongoose": "^5.11.14",
    "multer": "^1.4.2",
    "nodemon": "^2.0.7",
    "path": "^0.12.7"
  }
}

Now We will start the coding part from here First We will download hbs using npm install hbs . So First We will make the connection part of Nodejs with MongoDB. Create a folder named db inside the root folder of Nodejs. Now create a file inside db folder named conn.js

conn.js

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/StudentRecord',
  {
    useNewUrlParser:true,
    useUnifiedTopology:true,
    useCreateIndex:true,
    useFindAndModify:false
  }).then(()=>{
     console.log("Run Succefully");
  }).catch(()=>{
    console.log("Error in the code");    
  })

  

Now We will create a index.js file here we will set path, PORT number ,File Path and URL for the project.

index.js

const express = require('express')
const app = express();
const hbs = require('hbs'); 
const path = require('path');
const bodyParser = require('body-parser'); 
const fs = require('fs');
const multer = require('multer');

const upload_file = require('./helpers/image_helper.js') // It has Code for Image 

//const image_file = require('./helpers/file_helper.js');

app.use(bodyParser.urlencoded({ extended: true })); 

require("./db/conn");
const Student = require('./model/student'); 
const port = process.env.port || 5000;

app.use(express.static('./assets/images')); 
//app.use(express.static('./assets/files'));  

app.set('view engine','hbs');
app.set("views",path.join(__dirname,"./views/layouts"));

// Dsiplay Data 
var display = Student.find({});
 app.get('/',function(req,res,next){ 
    display.exec(function(err,data){
        if(err)throw err;
        console.log(data)
         res.render('index',{title:'Employee Record',records:data});
    });
}); 
// Insert Data
app.post('/insert',upload_file.single('image'),function (req,res){

    
    //fileSave();
    console.log(req.file);
    var data = new Student();

    data.name = req.body.name;
    data.email = req.body.email;
    data.mobile = req.body.mobile;
    data.roll = req.body.roll;
    data.gender = req.body.gender;
    data.image_file = req.file.filename;
    var save = data.save();
      
    if (save)
       res.redirect('/');
    else
    console.log('Error during record insertion : ' + err);  
   });

app.get('/:id',function(req,res){
   Student.findByIdAndRemove(req.params.id,(err,doc)=>{
      if (!err)
        {
        res.redirect('/');
        }
      else 
        {
        console.log('Failed to Delete Course Details: ' + err);
        }
   });
}); 

// To show select data on update element on edit.hbs page

app.get('/edit/:id', (req, res) => {
   Student.findById({_id:req.params.id},req.body, { new: true },(err,docs)=>{
      if(err)
      {
          console.log('Cant retrieve date and edit');
      }
      else
      {
          res.render('edit',{club:docs});
      }
   })
});

// Now Update Data here using ID

app.post('/update/:id',(req,res)=>{
     Student.findByIdAndUpdate({_id:req.params.id},req.body,(err,docs)=>{
         if(err)
         {
             console.log('Error');
         }  
         else
         {  
             res.redirect('/index');
         }
     });
});

app.listen(port,()=>{
    console.log('Listening on Port:',port);
});

Now create Two files inside view/layouts folder First file is index.hbs and edit.hbs ( views/layouts/index.hbs and views/layouts/edit.hbs ). Index.js is landing page and edit.hbs is edit page .

index.hbs

<html lang="en">
<head>
  <title>CRUD</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css"/>
</head>
<body style="background-color: whitesmoke;">

<div class="card text-center text-white" style="padding:15px;background-color:black">
  <h4>Update Student Records online using Nodejs</h4>
</div><br> 

<div class="container-fluid">   
  <div class="row">
   <div class="col-sm-4">
     <form action="/insert" method="POST" enctype="multipart/form-data">   
     <h5 class="text-center mt-4">Insert Record</h5>
      <div class="row  p-4" style="border: 1px solid #767676!important;">  
        <div class="col-sm-5">
           <div class="card">
            <div class="card-body">
              <input type="file" name="image" class="custom-file-input" id="inputGroupFile01"  onchange="document.getElementById('image').src = window.URL.createObjectURL(this.files[0])" aria-describedby="inputGroupFileAddon01">
              <label class="custom-file-label" for="inputGroupFile01">Photo</label>
               <img src=""  class="img-thumbnail" id="image">
            </div>
          </div>
          <p class="mt-3" style="font-size:small;font-weight:600">Upload Answer Sheet</p>
        </div>

        <div class="col-sm-7"> 
            <div class="form-group">
               <input type="text" class="form-control  mb-4" name="name" placeholder="Enter name" required="">
            </div>
             
            <div class="form-group">
               <input type="email" class="form-control  mb-4" name="email" placeholder="Enter email" required="">
            </div>

            <div class="form-group">
               <input type="text" class="form-control mb-4" name="roll" placeholder="Enter Roll No" required="">
            </div>

             {{!-- <input type="file" name="image_file" class="" id="inputGroupFile01"> --}}
          
            <div class="form-group">
               <input type="text" class="form-control mb-4" name="mobile" placeholder="Enter Mobile" required="">
            </div>

           <div class="form-check">
            <input class="form-check-input" type="radio" name="gender" id="exampleRadios1" style="cursor:pointer;" value="male">
              <label class="form-check-label" for="exampleRadios1">
                 Male
              </label>
              <input class="form-check-input ml-4" type="radio" name="gender" id="exampleRadios1" style="cursor:pointer;" value="female">
              <label class="form-check-label ml-5" for="exampleRadios1">
                 Female
              </label>
            </div>
            
            <input type="submit" name="submit" class="btn btn-primary btn-block mt-4" style="float:right;" value="Submit">
           
          </div>
      </div>
       </form>  
  </div>

  <div class="col-sm-8">
    <h4 class="text-center  ml-4 mt-4  mb-5">View Records</h4>
    <table class="table table-hover table-bordered ml-4 ">
        <thead>
        <tr>
            <th>Name</th>
            <th>Email</th>
            <th>Roll No</th>
            <th>Mobile</th>
            <th>Geneder</th>
            <th>Image</th>
            <th>Action</th>
        </tr>
        </thead>
        <tbody>

         {{#each records}}
            <tr>
            <td>{{name}}</td>
            <td>{{email}}</td>
            <td>{{roll}}</td>
            <td>{{mobile}}</td>
            <td>{{gender}}</td>
            <td><img src="{{{image_file}}}"  class="img-thumbnail" id="image" height="150" width="75"></td>
            <td><a href="/{{id}}" onclick="return confirm('Are you sure to delete this record ?');" class="fa fa-trash">
                </a>
                <a href="edit/{{id}}" class="fa fa-edit"></a>     
            </td>

            </tr>
            {{/each}}
        </tbody>
    </table>
  </div>
 </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>

edit.hbs

<html lang="en">
<head>
  <title>CRUD</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css"/>
</head>
<body>

<div class="card text-center" style="padding:15px;">
  <h4>Update Student Records online using Nodejs</h4>
</div><br> 

<div class="container-fluid">   
  <div class="row">  
    <div class="col-sm-8">
     <h4 class="text-center mb-5">Update Records</h4>
     <form action="/update/{{club.id}}" method="POST" enctype="multipart/form-data"></form>
     <table class="table table-hover table-bordered">
        <thead>
        <tr>
            <th>Name</th>
            <th>Email</th>
            <th>Roll No</th>
            <th>Mobile</th>
            <th>Geneder</th>
            <th>Image</th>
            <th>Action</th>
        </tr>
        </thead>
        <tbody>
            <tr>
              <td><input type="text" name="name" value="{{club.name}}"></td>
              <td><input type="text" name="email" value="{{club.email}}"></td>
              <td><input type="text" name="user" value="{{club.roll}}"></td>
              <td><input type="text" name="user" value="{{club.mobile}}"></td>
              {{!-- <td><input type="text" name="user" value="{{club.gender}}"></td> --}}
              <td><input type="text" name="user" value="{{club.gender}}"> </td>
              <td><img src="{{{club.image_file}}}"  class="img-thumbnail" id="image" height="150" width="80"></td>
              <td><button type="submit" class="btn btn-primary" onclick="return confirm('Are you sure to Update this record ?')">update</button></td>
            </tr>
        </tbody>
      </table>
     </form> 
   </div>
 </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>

Now Create a Query file Where we will create Fields list and assign its type. So We will create a file named student.js ( models/student.js) .

const mongoose = require('mongoose');

var scheme = new mongoose.Schema({
   
    name : {
        type: String,
        unique : false,
        required : true
    },
    email : {
        type: String,
        unique : false,
        required : true
    },
    mobile : {
        type: String,
        unique : false,
        required : true
    },
    roll : {
        type: String,
        unique : false,
        required : true
    },
    gender :
    {
        type: String
    },
    image_file :
    {
        type: String,
        unique : false
    }
});

var Student = mongoose.model("student_records", scheme);

module.exports = Student;

Now create a file for Image helper Where we will write code for Image Upload ( helper/image_helper.js ) and IMAGES will store in images folder ( assets/images )

helper/image_helper.js

const multer = require('multer');

var storage =   multer.diskStorage({  
  destination: function (req, file, callback) {  
    callback(null, './assets/images');  
  },  
  filename: function(req, file, callback) {
    console.log(file);
    if(file.originalname.length>6)
      callback(null, file.fieldname + '-' + Date.now() + file.originalname.substr(file.originalname.length-6,file.originalname.length));
    else
      callback(null, file.fieldname + '-' + Date.now() + file.originalname);

  }
});  
var upload = multer({ storage : storage});  

 module.exports = upload;

In above code we have created some setting for file upload and assign its path where images will be saved.

Now Run the code in browser using node.index.js It will run on PORT Number 5000 . http://localhost:5000

Download Source Code : Nodejs CRUD

Read Our More Articles

How to Load millions record in React

May 12, 2021REACT JSUncategorizedComments: 0

I will show you how you can load 1 million records in Reactjs .How to Load millions record in React In this blog post, we are going to discuss how to load more than a million records in less than a second in ReactJS.I will use JSON Server as a database you can use MYSQL …

Read more

Building an Image Gallery with Laravel and React

May 11, 2021LARAVELREACT JSComments: 0

Today we are building an image gallery with Laravel and React. Building an Image Gallery with Laravel and React. [download_after_email id=”833″] Now Start from Frontend part So we will making our ReactJS Project . To Install React project run this command in your cmd or terminal npx create-react-app image_galllary . Reactjs or Angular and Any …

Read more

How to search records in ReactJS

May 7, 2021REACT JSComments: 0

In this article, I am going to show you from scratch how to implement a searchable/filtered list of data in React.How to search records in ReactJS. We will create a search form in ReactJS Using this form We can search any record. We will work in Functional Components, not class components. Read more about React …

Read more

How To Create Charts In React With Database

Leave a Reply

Your email address will not be published. Required fields are marked *