CRUD Operation Using React, Nodejs, Express, MongoDb

Today, I am sharing how to perform CRUD operations using React, Nodejs, Express, and MongoDB. it's really interesting to create applications using React, Node.js, and MongoDB. This article goes step by step.
 

Introduction

 
In this article, we will create a demo project using React for Front-end, Node.js and Express for middle-end, and MongoDB for the back-end. Below is information in brief about React, Nodejs, Express, and MongoDB.
  • React is a front-end library developed by Facebook. It's used for handling front end for web and mobile apps. ReactJS allows us to create reusable UI components.
  • Node is an open-source server framework.It is used to develop I/O intensive web applications like video streaming sites, single-page applications, and other web applications.
  • Express is a web framework for Node.js. It is fast, robust, and asynchronous in nature.
  • MongoDB is a No SQL database. It is an open-source, cross-platform, document-oriented database written in C++.
Prerequisites
  • Basic Knowledge of Nodejs API’S.
  • Basic Knowledge of Mongodb Query and mongoose.
  • Basic Knowledge of Ajax, JSON.
Requirement
 
Node,Mongodb,React js,Any IDE for mongodb,VScode ,Any command prompt (i suggest Git Bash) etc.
 
Here is the Step by Step write code.
 
Step 1
 
Create New Folder, ReactCRUD, if you use git then right-click folder then GIT Bash runs command npm init. If you use cmd you navigate to your folder after running this command.
  1. npm init  
Step 2
 
One by one put answers by cmd: your project name, keyword, entry point etc. After creating your package.json file code like this.
  1. {  
  2.   "name""reactcrud",  
  3.   "version""1.0.0",  
  4.   "description""reactCrud",  
  5.   "main""server.js",  
  6.   "scripts": {  
  7.     "test""react"  
  8.   },  
  9.   "keywords": [  
  10.     "React"  
  11.   ],  
  12.   "author""puneet kankar",  
  13.   "license""MIT"  
  14.   
  15. }  
Step 3 
 
Add manual dependencies or one by one in our package.json express,mongoose,morgan,body-parser etc.
  1. {  
  2.   "name""reactcrud",  
  3.   "version""1.0.0",  
  4.   "description""reactCrud",  
  5.   "main""server.js",  
  6.   "scripts": {  
  7.     "test""react"  
  8.   },  
  9.   "keywords": [  
  10.     "React"  
  11.   ],  
  12.   "author""puneet kankar",  
  13.   "license""MIT",  
  14.    "dependencies": {  
  15.     "body-parser""^1.17.2",     
  16.     "express""^4.15.3",      
  17.     "mongoose""^4.10.2",  
  18.     "morgan""^1.8.2"  
  19.       
  20.   }  
  21. }  
Step 4
 
Run npm install command . If you went one by one add dependencies run these commands one by one.
  1. // when you add manual dependencies in package.json  
  2. npm init   
  3.   
  4. //or   
  5.   
  6. // when you not add dependencies in package.json  
  7. npm install body-parser  
  8. npm install express  
  9. npm install mongoose  
  10. npm install morgan  
Step 5 
 
We Create config.js file on root directory for Mongodb database connection.We write code like this. In this code we require mongoose driver for connection to database. 
  1. var mongo = require("mongoose");  
  2. var db =   
  3. mongo.connect("mongodb://192.168.1.71:27017/reactcrud"function(err, response){  
  4.    if(err){ console.log('Failed to connect to ' + db); }  
  5.    else{ console.log('Connected to ' + db, ' + ', response); }  
  6. });  
  7.   
  8.   
  9. module.exports =db;  
  10.   
  11. // reactcrud is database name  
  12. // 192.168.1.71:27017 is your mongo server name  
Step 6
 
We Create server.js file on root directory for writing nodejs apis for our Create ,Insert,Delete,Update. Give port number for application and run on server. In this file we write the code for all required dependancies and create schema of our database collection document and write code for api's for performing operation.
  1. var express = require("express");  
  2. var path = require("path");  
  3. var mongo = require("mongoose");   
  4. var bodyParser = require('body-parser');   
  5. var morgan = require("morgan");  
  6. var db = require("./config.js");  
  7.   
  8. var app = express();  
  9. var port = process.env.port || 7777;  
  10. var srcpath  =path.join(__dirname,'/public') ;  
  11. app.use(express.static('public'));  
  12. app.use(bodyParser.json({limit:'5mb'}));    
  13. app.use(bodyParser.urlencoded({extended:true, limit:'5mb'}));  
  14.   
  15.   
  16. var mongoose = require('mongoose');  
  17. var Schema = mongoose.Schema;  
  18. var studentSchema = new Schema({      
  19.     name: { type: String   },       
  20.     address: { type: String   },     
  21.     email: { type: String },       
  22.     contact: { type: String },       
  23. },{ versionKey: false });  
  24.    
  25.   
  26. var model = mongoose.model('student', studentSchema, 'student');  
  27.   
  28. //api for get data from database  
  29. app.get("/api/getdata",function(req,res){   
  30.  model.find({},function(err,data){  
  31.             if(err){  
  32.                 res.send(err);  
  33.             }  
  34.             else{             
  35.                 res.send(data);  
  36.                 }  
  37.         });  
  38. })  
  39.   
  40.   
  41. //api for Delete data from database  
  42. app.post("/api/Removedata",function(req,res){   
  43.  model.remove({ _id: req.body.id }, function(err) {  
  44.             if(err){  
  45.                 res.send(err);  
  46.             }  
  47.             else{    
  48.                    res.send({data:"Record has been Deleted..!!"});             
  49.                }  
  50.         });  
  51. })  
  52.   
  53.   
  54. //api for Update data from database  
  55. app.post("/api/Updatedata",function(req,res){   
  56.  model.findByIdAndUpdate(req.body.id, { name:  req.body.name, address: req.body.address, contact: req.body.contact,email:req.body.email },   
  57. function(err) {  
  58.  if (err) {  
  59.  res.send(err);  
  60.  return;  
  61.  }  
  62.  res.send({data:"Record has been Updated..!!"});  
  63.  });  
  64. })    
  65.   
  66.   
  67. //api for Insert data from database  
  68. app.post("/api/savedata",function(req,res){   
  69.        
  70.     var mod = new model(req.body);  
  71.         mod.save(function(err,data){  
  72.             if(err){  
  73.                 res.send(err);                
  74.             }  
  75.             else{        
  76.                  res.send({data:"Record has been Inserted..!!"});  
  77.             }  
  78.         });  
  79. })  
  80.       
  81. // call by default index.html page  
  82. app.get("*",function(req,res){   
  83.     res.sendFile(srcpath +'/index.html');  
  84. })  
  85.   
  86. //server stat on given port  
  87. app.listen(port,function(){   
  88.     console.log("server start on port"+ port);  
  89. })  
Step 7
 
We create new public folder. Inside this folder create new HTML file with name index.html. We include react js ,react-dom ,babel,bootstrap CSS,jquery link as we require in our application.
  1. <!DOCTYPE HTML>    
  2. <html>    
  3.     <head>    
  4.       <meta charset="utf-8">    
  5.        <title>React CRUD</title>    
  6.        <script src="https://fb.me/react-15.0.1.js"></script>    
  7.        <script src="https://fb.me/react-dom-15.0.1.js"></script>    
  8.        <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>    
  9.        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">  
  10.       <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>  
  11.     </head>    
  12.      <body>   
  13.      <div  id='root'></div>        
  14.      <script type="text/babel"  src="./ReactCrud.jsx"  >     
  15.      </script>    
  16.     </body>    
  17. </html>    
Step 8
 
We create ReactCrud.jsx file for create component with the name StudentAll. Here we write code for insert , select, update, delete operation API calling code.
  1.    
  2. var StudentAll = React.createClass({   
  3.   
  4.   getInitialState: function () {  
  5.     return { name: '' ,address: '',email:'',contact:'',id:'',Buttontxt:'Save', data1: []};  
  6.   },  
  7.    handleChange: function(e) {  
  8.         this.setState({[e.target.name]: e.target.value});  
  9.     },  
  10.   
  11.   componentDidMount() {  
  12.    
  13.     $.ajax({  
  14.        url: "api/getdata",  
  15.        type: "GET",  
  16.        dataType: 'json',  
  17.        ContentType: 'application/json',  
  18.        success: function(data) {           
  19.          this.setState({data1: data});   
  20.            
  21.        }.bind(this),  
  22.        error: function(jqXHR) {  
  23.          console.log(jqXHR);  
  24.              
  25.        }.bind(this)  
  26.     });  
  27.   },  
  28.     
  29. DeleteData(id){  
  30.   var studentDelete = {  
  31.         'id': id  
  32.            };        
  33.     $.ajax({  
  34.       url: "/api/Removedata/",  
  35.       dataType: 'json',  
  36.       type: 'POST',  
  37.       data: studentDelete,  
  38.       success: function(data) {  
  39.         alert(data.data);  
  40.          this.componentDidMount();  
  41.   
  42.       }.bind(this),  
  43.       error: function(xhr, status, err) {  
  44.          alert(err);   
  45.              
  46.             
  47.       }.bind(this),  
  48.       });  
  49.     },  
  50.    
  51.     EditData(item){           
  52.    this.setState({name: item.name,address:item.address,contact:item.contact,email:item.email,id:item._id,Buttontxt:'Update'});  
  53.      },  
  54.   
  55.    handleClick: function() {  
  56.    
  57.    var Url="";  
  58.    if(this.state.Buttontxt=="Save"){  
  59.       Url="/api/savedata";  
  60.        }  
  61.       else{  
  62.       Url="/api/Updatedata";  
  63.       }  
  64.       var studentdata = {  
  65.         'name'this.state.name,  
  66.         'address':this.state.address,  
  67.         'email':this.state.email,  
  68.         'contact':this.state.contact,  
  69.         'id':this.state.id,  
  70.           
  71.     }  
  72.     $.ajax({  
  73.       url: Url,  
  74.       dataType: 'json',  
  75.       type: 'POST',  
  76.       data: studentdata,  
  77.       success: function(data) {         
  78.           alert(data.data);         
  79.           this.setState(this.getInitialState());  
  80.           this.componentDidMount();  
  81.            
  82.       }.bind(this),  
  83.       error: function(xhr, status, err) {  
  84.          alert(err);       
  85.       }.bind(this)  
  86.     });  
  87.   },  
  88.   
  89.   render: function() {  
  90.     return (   
  91.       <div  className="container"  style={{marginTop:'50px'}}>  
  92.        <p className="text-center" style={{fontSize:'25px'}}><b> CRUD Opration Using React,Nodejs,Express,MongoDB</b></p>  
  93.   <form>  
  94.     <div className="col-sm-12 col-md-12"  style={{marginLeft:'400px'}}>   
  95.   <table className="table-bordered">  
  96.      <tbody>  
  97.     <tr>  
  98.       <td><b>Name</b></td>  
  99.       <td>  
  100.          <input className="form-control" type="text" value={this.state.name}    name="name" onChange={ this.handleChange } />  
  101.           <input type="hidden" value={this.state.id}    name="id"  />  
  102.       </td>  
  103.     </tr>  
  104.   
  105.     <tr>  
  106.       <td><b>Address</b></td>  
  107.       <td>  
  108.       <input type="text" className="form-control" value={this.state.address}  name="address" onChange={ this.handleChange } />  
  109.       </td>  
  110.     </tr>  
  111.   
  112.     <tr>  
  113.       <td><b>Email</b></td>  
  114.       <td>  
  115.         <input type="text"  className="form-control" value={this.state.email}  name="email" onChange={ this.handleChange } />  
  116.       </td>  
  117.     </tr>  
  118.   
  119.   
  120.     <tr>  
  121.       <td><b>Contact</b></td>  
  122.       <td>  
  123.         <input type="text"  className="form-control" value={this.state.contact}  name="contact" onChange={ this.handleChange } />  
  124.       </td>  
  125.     </tr>  
  126.   
  127.     <tr>  
  128.       <td></td>  
  129.       <td>  
  130.         <input className="btn btn-primary" type="button" value={this.state.Buttontxt} onClick={this.handleClick} />  
  131.       </td>  
  132.     </tr>  
  133.   
  134.  </tbody>  
  135.     </table>  
  136. </div>  
  137.    
  138.   
  139. <div className="col-sm-12 col-md-12 "  style={{marginTop:'50px',marginLeft:'300px'}} >  
  140.    
  141.  <table className="table-bordered"><tbody>  
  142.    <tr><th><b>S.No</b></th><th><b>NAME</b></th><th><b>ADDRESS</b></th><th><b>EMAIL</b></th><th><b>CONTACT</b></th><th><b>Edit</b></th><th><b>Delete</b></th></tr>  
  143.     {this.state.data1.map((item, index) => (  
  144.         <tr key={index}>  
  145.            <td>{index+1}</td>   
  146.           <td>{item.name}</td>                        
  147.           <td>{item.address}</td>  
  148.           <td>{item.email}</td>  
  149.           <td>{item.contact}</td>  
  150.            <td>   
  151.             
  152.            <button type="button" className="btn btn-success" onClick={(e) => {this.EditData(item)}}>Edit</button>      
  153.           </td>   
  154.           <td>   
  155.              <button type="button" className="btn btn-info" onClick={(e) => {this.DeleteData(item._id)}}>Delete</button>  
  156.           </td>   
  157.         </tr>  
  158.     ))}  
  159.     </tbody>  
  160.     </table>  
  161.      </div>  
  162. </form>          
  163.       </div>  
  164.     );  
  165.   }  
  166. });  
  167.   
  168. ReactDOM.render(<StudentAll  />, document.getElementById('root'))  
Step 9
 
We are almost finished with all the required tasks. We are going to command prompt run node server.js or if you are installing morgan then use nodemon server.
 
 
Step 10
 
We will go and browse our application on given port number 7777 in our server.js file so we run this URL http://localhost:7777/  our output display looks like below image.
 
 
I have attached rar file in this demonstration below. Please find the file if you want an application code.
 

Summary

 
I hope we learned how to create basic crud operation using React, Nodejs, MongoDB, Express, etc step by step.i hope you enjoy this article. Thank you for reading.
 
If you have any questions/ feedback please write in the comment box.