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. const curdSchema= new mongoose.Schema({
  3. name: String
  4. })
  5. 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. const app =express();
  6. mongoose.connect('mongodb://localhost:27017/curdDemo')
  7. .then(()=>console.log('connected')).catch(err=>console.log(err))
  8. //setting template engine //
  9. app.set('view engine','ejs');
  10. //for fetching FORMDATA from coming request //
  11. app.use(bodyParser.urlencoded({extended:false}))
  12. //READ DATA
  13. app.get('/',(req,res)=>{
  14. curd.find((err,data)=>{
  15. if(err){
  16. console.log(err)
  17. }
  18. else if(!data){
  19. res.render('home',{data:{}})
  20. }
  21. else{
  22. res.render('home',{data:data})
  23. }
  24. })
  25. })
  26. //ADD DATA //
  27. app.post('/add',(req,res)=>{
  28. const curds = new curd({
  29. name: req.body.uname
  30. })
  31. curds.save((err,data)=>{
  32. if(err){
  33. console.log(err)
  34. }
  35. res.redirect('/')
  36. })
  37. })
  38. //EDIT DATA //
  39. app.get('/edit/:id',(req,res)=>{
  40. curd.find({_id:req.params.id},(err,data)=>{
  41. if(err){
  42. console.log(err)
  43. }
  44. console.log('edit data',data)
  45. res.render('edit',{edata:data})
  46. })
  47. })
  48. //UPDATE DATA //
  49. app.post('/update',(req,res)=>{
  50. const upCURD = {
  51. name : req.body.uname
  52. }
  53. curd.update({_id:req.body.id},{$set:upCURD},(err,data)=>{
  54. if(err){
  55. console.log('update error',err)
  56. }
  57. console.log(data)
  58. res.redirect('/')
  59. })
  60. })
  61. //DELETE DATA //
  62. app.get('/delete/:id',(req,res)=>{
  63. curd.deleteOne({_id:req.params.id},(err,data)=>{
  64. if(err){
  65. console.log(err)
  66. }
  67. res.redirect('/')
  68. })
  69. })
  70. const port = process.env.PORT || 3000 ;
  71. app.listen(port,()=>console.log(`server running at ${port}`))
  72. 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. <!-- THIS SECTION WILL ONLY BE SHOWN WHEN data WILL NOT BE EMPTY -->
  18. <% if (data.length > 0) {%>
  19. <table>
  20. <thead>
  21. <tr><th>Name</th>
  22. <th>edit</th>
  23. <th>delete</th>
  24. </tr>
  25. </thead>
  26. <tbody>
  27. <% data.forEach(function(data, index) { %>
  28. <tr>
  29. <td> <%= data.name %> </td>
  30. <!-- WHEN WE CLICK EDIT THEN WE WILL BE ROUTES TO EDIT PAGE -->
  31. <!-- THE EDIT ROUTE IS TAKING ID AS A PARAMETER WITH ITSELF -->
  32. <td><a href="/edit/<%= data._id %>">edit</a></td>
  33. <!-- DELETE WILL ALSO TAKE ID AS PARAMETER AND WILL REDIRECT TO CURRENT PAGE AFTER DELETING THE DATA -->
  34. <td><a href="/delete/<%= data._id %>">delete</a></td>
  35. </tr>
  36. <% }) %>
  37. </tbody>
  38. </table>
  39. <% } %>
  40. </body>
  41. </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. </body>
  27. </html>