In Focus

CRUD Operation Using React, Nodejs, Express, MongoDb

In this article, we will create a demo project using React for front-end,nodejs and express for middle-end, and Mongodb for back-end.

Today, I am sharing how to perform CRUD operations using React, Nodejs, Express, and MogoDB. 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 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 a 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 Knowleage of Nodejs API’S.
  • Basic Knowleage of Mongodb Query and mongoose.
  • Basic Knowleage 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 name StudentAll. Here we write code for insert ,select ,update,delete opration 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.   
  52.   
  53.     EditData(item){           
  54.    this.setState({name: item.name,address:item.address,contact:item.contact,email:item.email,id:item._id,Buttontxt:'Update'});  
  55.      },  
  56.   
  57.    handleClick: function() {  
  58.    
  59.    var Url="";  
  60.    if(this.state.Buttontxt=="Save"){  
  61.       Url="/api/savedata";  
  62.        }  
  63.       else{  
  64.       Url="/api/Updatedata";  
  65.       }  
  66.       var studentdata = {  
  67.         'name'this.state.name,  
  68.         'address':this.state.address,  
  69.         'email':this.state.email,  
  70.         'contact':this.state.contact,  
  71.         'id':this.state.id,  
  72.           
  73.     }  
  74.     $.ajax({  
  75.       url: Url,  
  76.       dataType: 'json',  
  77.       type: 'POST',  
  78.       data: studentdata,  
  79.       success: function(data) {         
  80.           alert(data.data);         
  81.           this.setState(this.getInitialState());  
  82.           this.componentDidMount();  
  83.            
  84.       }.bind(this),  
  85.       error: function(xhr, status, err) {  
  86.          alert(err);       
  87.       }.bind(this)  
  88.     });  
  89.   },  
  90.   
  91.   render: function() {  
  92.     return (   
  93.       <div  className="container"  style={{marginTop:'50px'}}>  
  94.        <p className="text-center" style={{fontSize:'25px'}}><b> CRUD Opration Using React,Nodejs,Express,MongoDB</b></p>  
  95.   <form>  
  96.     <div className="col-sm-12 col-md-12"  style={{marginLeft:'400px'}}>   
  97.   <table className="table-bordered">  
  98.      <tbody>  
  99.     <tr>  
  100.       <td><b>Name</b></td>  
  101.       <td>  
  102.          <input className="form-control" type="text" value={this.state.name}    name="name" onChange={ this.handleChange } />  
  103.           <input type="hidden" value={this.state.id}    name="id"  />  
  104.       </td>  
  105.     </tr>  
  106.   
  107.     <tr>  
  108.       <td><b>Address</b></td>  
  109.       <td>  
  110.       <input type="text" className="form-control" value={this.state.address}  name="address" onChange={ this.handleChange } />  
  111.       </td>  
  112.     </tr>  
  113.   
  114.     <tr>  
  115.       <td><b>Email</b></td>  
  116.       <td>  
  117.         <input type="text"  className="form-control" value={this.state.email}  name="email" onChange={ this.handleChange } />  
  118.       </td>  
  119.     </tr>  
  120.   
  121.   
  122.     <tr>  
  123.       <td><b>Contact</b></td>  
  124.       <td>  
  125.         <input type="text"  className="form-control" value={this.state.contact}  name="contact" onChange={ this.handleChange } />  
  126.       </td>  
  127.     </tr>  
  128.   
  129.     <tr>  
  130.       <td></td>  
  131.       <td>  
  132.         <input className="btn btn-primary" type="button" value={this.state.Buttontxt} onClick={this.handleClick} />  
  133.       </td>  
  134.     </tr>  
  135.   
  136.  </tbody>  
  137.     </table>  
  138. </div>  
  139.    
  140.   
  141. <div className="col-sm-12 col-md-12 "  style={{marginTop:'50px',marginLeft:'300px'}} >  
  142.    
  143.  <table className="table-bordered"><tbody>  
  144.    <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>  
  145.     {this.state.data1.map((item, index) => (  
  146.         <tr key={index}>  
  147.            <td>{index+1}</td>   
  148.           <td>{item.name}</td>                        
  149.           <td>{item.address}</td>  
  150.           <td>{item.email}</td>  
  151.           <td>{item.contact}</td>  
  152.            <td>   
  153.             
  154.            <button type="button" className="btn btn-success" onClick={(e) => {this.EditData(item)}}>Edit</button>      
  155.           </td>   
  156.           <td>   
  157.              <button type="button" className="btn btn-info" onClick={(e) => {this.DeleteData(item._id)}}>Delete</button>  
  158.           </td>   
  159.         </tr>  
  160.     ))}  
  161.     </tbody>  
  162.     </table>  
  163.      </div>  
  164. </form>          
  165.       </div>  
  166.     );  
  167.   }  
  168. });  
  169.   
  170. ReactDOM.render(<StudentAll  />, document.getElementById('root'))  
Step 9

We are almost finished with all required tasks.We are goning 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 file if you want application code.

Summary

I hope we learned how to create basic crud opration using React,Nodejs,mongodb,express etc step by step.i hope you enjoy this article.Thank you for watching.

If you have any questions/ feedback please write in the comment box.