CURD Operation In Node

Setup Node On System

  • If you don't have node installed on your system then you can download it from here https://nodejs.org/en/.
  • After installing the node on system , open cmd and type node-v
  • It will give node version like this,
 
 

Setup MongoDB On System

Setup Our Node Project

  • Create a new folder nodecurd
  • Change to the folder to nodecurd
  • Type npm init to setup node project.
  • A package.json file will automatically get added in the project.
  • Now type npm install for adding node packages.
  • npm install express mongoose body-parser ejs
         A little info about the packages,
  • express - It is a framework and all the applications will be built on it.
  • body-parser - This will fetch FormData from the request.
  • mongoose - this will be used for setting connections with a database.
  • ejs - This is a view engine. The view engine is responsible for creating HTML from your views.
 
  • Views are usually some kind of mixup of HTML and a programming language.
  • Now open the project in editor and you will see package.json which will be automatically generated 
  • Then open package.json and write "start" : "app.js" this will be the starting point of the application.
 
 
    Make 2 folders
  • models
  • views
      *as mentioned above the views will contain .ejs files.which will contain HTML and databindings using ejs.
 
 

Models

  • The models will contain the collections(table) schema
  • Here we will make a collection named empdata having field name
  1. const mongoose = require('mongoose');  
  2.   
  3. const curdSchema= new mongoose.Schema({  
  4.     name: String  
  5. })  
  6.   
  7. module.exports=mongoose.model('empdata',curdSchema)  

App.js

  1. const express= require('express');  
  2. const mongoose = require('mongoose');  
  3. const bodyParser = require('body-parser');  
  4. const curd  = require('./models/curd');    
  5.   
  6.   
  7. const app =express();  
  8.   
  9. mongoose.connect('mongodb://localhost:27017/curdDemo')  
  10. .then(()=>console.log('connected')).catch(err=>console.log(err))  
  11.   
  12. //setting template engine //  
  13. app.set('view engine','ejs');  
  14.   
  15. //for fetching FORMDATA from coming request //  
  16. app.use(bodyParser.urlencoded({extended:false}))  
  17.   
  18. //READ DATA   
  19. app.get('/',(req,res)=>{  
  20.   curd.find((err,data)=>{  
  21.       if(err){  
  22.           console.log(err)  
  23.       }  
  24.     else if(!data){  
  25.         res.render('home',{data:{}})  
  26.     }  
  27.     else{  
  28.        res.render('home',{data:data})     
  29.     }  
  30.   })  
  31. })  
  32.   
  33. //ADD DATA //  
  34. app.post('/add',(req,res)=>{  
  35.     const curds =  new curd({  
  36.         name: req.body.uname  
  37.     })  
  38.     curds.save((err,data)=>{  
  39.         if(err){  
  40.             console.log(err)  
  41.         }  
  42.         res.redirect('/')  
  43.     })  
  44. })  
  45.   
  46.   
  47. //EDIT DATA //  
  48. app.get('/edit/:id',(req,res)=>{  
  49.     curd.find({_id:req.params.id},(err,data)=>{  
  50.              if(err){  
  51.                  console.log(err)  
  52.              }  
  53.              console.log('edit data',data)  
  54.              res.render('edit',{edata:data})  
  55.     })  
  56. })  
  57.   
  58. //UPDATE DATA //  
  59. app.post('/update',(req,res)=>{  
  60.     const upCURD = {  
  61.         name : req.body.uname  
  62.     }  
  63.     curd.update({_id:req.body.id},{$set:upCURD},(err,data)=>{  
  64.         if(err){  
  65.             console.log('update error',err)  
  66.         }  
  67.         console.log(data)  
  68.         res.redirect('/')  
  69.     })  
  70. })  
  71.   
  72. //DELETE DATA //  
  73. app.get('/delete/:id',(req,res)=>{  
  74.     curd.deleteOne({_id:req.params.id},(err,data)=>{  
  75.         if(err){  
  76.             console.log(err)  
  77.         }  
  78.         res.redirect('/')  
  79.     })  
  80. })  
  81.   
  82.   
  83.   
  84. const port = process.env.PORT || 3000 ;  
  85. app.listen(port,()=>console.log(`server running at ${port}`))  
  86.   
  87. module.exports=app;  
  • Here we import package mongoose,body-parser,express using require() function.
  • We also import the model we made in models folder. Using it we can access  all mongodb functions for doing data manipulation.
  • mongoose.connect() is used for making connection with mongodb. The curdDemo in the connection here is the name of our database.
  • We will set the view engine using app.set(). The view engine will tell the express which engine we are using in our project for views.
  • app.use() is a middleware which checks every request and response. And the body-parser will look for the FormData in the request which will come. 

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.     <!-- THE DATA WE SENDING IN FORM WILL BE FETCH FROM REQUEST BY THE NAME WE GIVEN IN TAGS -->  
  10.     <h2>Add Data</h2>  
  11.     <form action="/add" method="POST">  
  12.        <label for="unmae">Enter Name</label>  
  13.        <input type="text" name="uname" required><br/>  
  14.        <button type="submit">save</button>  
  15.     </form>  
  16.     <br><br>  
  17.   
  18. <!-- THIS SECTION WILL ONLY BE SHOWN WHEN data WILL NOT BE EMPTY  -->      
  19.     <% if (data.length > 0) {%>  
  20.        <table>  
  21.            <thead>  
  22.            <tr><th>Name</th>  
  23.            <th>edit</th>  
  24.            <th>delete</th>  
  25.            </tr>  
  26.        </thead>  
  27.            <tbody>  
  28.                    <% data.forEach(function(data, index) { %>  
  29.                <tr>  
  30.                    <td> <%= data.name %>  </td>  
  31.                    <!-- WHEN WE CLICK EDIT THEN WE WILL BE ROUTES TO EDIT PAGE -->  
  32.                    <!-- THE EDIT ROUTE IS TAKING ID AS A PARAMETER WITH ITSELF -->  
  33.                    <td><a href="/edit/<%= data._id %>">edit</a></td>  
  34.                    <!-- DELETE WILL ALSO TAKE ID AS PARAMETER AND WILL REDIRECT TO CURRENT PAGE AFTER DELETING THE DATA -->  
  35.                    <td><a href="/delete/<%= data._id %>">delete</a></td>  
  36.                </tr>  
  37.                  
  38.                <% }) %>  
  39.            </tbody>  
  40.        </table>  
  41.        <% } %>  
  42. </body>  
  43. </html>  
edit.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.     <!-- FORM DATA WILL GOTO APP.POST('/UPDATE') ROUTE WHEN FORM IS SUBMITTED -->  
  10.     <h1>Edit Data</h1>  
  11.         <form action="/update" method="POST">  
  12.             <table>  
  13.                 <thead>  
  14.                 <tr><th>Name</th>  
  15.                 </tr>  
  16.              </thead>  
  17.                 <tbody>  
  18.                     <tr>  
  19.                         <td><input type="text" name="uname" value="<%= edata[0].name %>" >  </td>  
  20.                         <td><input type="hidden" name="id" value="<%= edata[0]._id %>"></td>  
  21.                         <td><input type="submit" value="submit"></td>  
  22.                     </tr>  
  23.                 </tbody>  
  24.              </table>  
  25.            </form>  
  26.           
  27. </body>  
  28. </html>