Professional Documents
Culture Documents
In this part of the article, we are going to learn about MERN stack, which is the trending technology stack nowadays,
you may have question like what is Difference between MEAN Stack and MERN Stack, so let me clarify that there is no
major difference between them except front-end technology so that here in this article you can skip Angular and
Consider React as front-end technology.
MongoDB
It is NoSql Database documents which act as a backend four our MERN stack web application.
ExpressJS
ExpressJS is a JavaScript-based backend web application framework and mostly used to create API for our MERN
stack app.
React
React is a JavaScript-based library which is used to build the powerful and attractive user interface; it has so many
features which make to unique among other front-end libraries like Virtual DOM.
NodeJS
NodeJS is a JavaScript-based run-time environment, which enables us to create a JavaScript-based back-end
environment and network applications.
The main attraction is that in MERN stack everything you write is somehow JavaScript. Starting from Database of
MongoDB, to the front-end technology which is React, so if you have enough knowledge of JavaScript then you will
find it pretty relevant to your technology stack.
In this article, we are going to cover all of the layers of MERN stack in a step by step manner.
Project Structure
As we have discussed earlier that our front-end will be a library called React and backend/server codes are related to
MongoDB, Express, and Nodejs, so for that, we have different folders structure based on the specific usage.
https://www.dotnettricks.com/learn/react/mern-stack-crud-operations-example 1/28
3/7/22, 3:48 PM MERN Stack CRUD Operations
Project Prerequisites
https://www.dotnettricks.com/learn/react/mern-stack-crud-operations-example 2/28
3/7/22, 3:48 PM MERN Stack CRUD Operations
To get started with MERN stack, we need to have installed the following tools and editors.
Install NodeJs
https://nodejs.org/en/download/
MongoDB
https://www.mongodb.com/download-center
Code Editor
To create and implement MERN stack application, we need to have any code editor will be installed like Visual Studio
Code, Visual Studio, Nuclide etc. I am going to use Microsoft Visual Studio Code for this tutorial.
When we done with the above tools, now to its time to install few important dependencies to work with Front-end and
back-end for MERN stack.
Front-end dependencies
Package Description
npm install For using different bootstrap components into our application
react-bootstrap
Back-end dependencies
Package Description
npm install Runs as a module for nodejs and useful for routing
express
npm install Parse the response data coming from API and validate before using into our application
body-parser
npm install cors To enable cors middleware using nodejs with various options
https://www.dotnettricks.com/learn/react/mern-stack-crud-operations-example 3/28
3/7/22, 3:48 PM MERN Stack CRUD Operations
Our first and basic requirement is to create a new react app using create-react-app which provides the sample
boilerplate project or we can say quickstart project. To create a new project, we need to install react using below npm
command.
Npm install –g create-react-app
Then you can see that our new project will be created and look like this.
Setup of Backend
https://www.dotnettricks.com/learn/react/mern-stack-crud-operations-example 4/28
3/7/22, 3:48 PM MERN Stack CRUD Operations
So far, we have installed all the necessary dependencies and tools to get started with MERN stack, now it’s time to set
up our backend so that we can use it into our front-end application.
path = require('path'),
bodyParser = require('body-parser'),
cors = require('cors'),
mongoose = require('mongoose');
mongoose.Promise = global.Promise;
);
app.use(bodyParser.json());
// Enabled CORS
app.use(cors());
// Routes Configuration
app.use('/employees', employeeRoutes);
});
https://www.dotnettricks.com/learn/react/mern-stack-crud-operations-example 5/28
3/7/22, 3:48 PM MERN Stack CRUD Operations
In the above file, I have imported all the dependencies what we have installed previously, apart from that imported few
files related to routing. But most important things are that we have connected our application to MongoDB using
below code.
);
As you can see that my database running on port number 27017 and my database name is employeeDetails.
MongoDB Model
In this tutorial, we are going to take an example table of Employee details like first name, last name, email etc, so for
that, we need to create the model schema. Create a new folder named Model and create a new file inside that named
Employee.js
firstName: {
type: String
},
lastName: {
type: String
},
email: {
type: String
},
phone: {
type: Number
},{
collection: 'employees'
});
https://www.dotnettricks.com/learn/react/mern-stack-crud-operations-example 6/28
3/7/22, 3:48 PM MERN Stack CRUD Operations
One of the most important parts of this MERN stack crud is to create REST API. For that, we need to create an API
controller based on the URL which the user is going to traverse. Create a new folder called Routes and inside the folder
create a new file named Employee.route.js.
https://www.dotnettricks.com/learn/react/mern-stack-crud-operations-example 7/28
3/7/22, 3:48 PM MERN Stack CRUD Operations
if (err) {
console.log(err);
else {
res.json(employee);
});
});
employee.save()
.then(game => {
})
.catch(err => {
});
});
let id = req.params.id;
res.json(employee);
});
});
if (!employee)
else {
employee.firstName = req.body.firstName;
employee.lastName = req.body.lastName;
employee.email = req.body.email;
https://www.dotnettricks.com/learn/react/mern-stack-crud-operations-example 8/28
3/7/22, 3:48 PM MERN Stack CRUD Operations
employee.phone = req.body.phone;
employee.save().then(emp => {
})
.catch(err => {
});
});
});
if (err) res.json(err);
});
});
module.exports = employeeRoute;
In this file, basically, I have created different API’s which are listed below.
API Description
We have created the list of API’s, now let’s test it using API testing tool named Postman.
https://www.dotnettricks.com/learn/react/mern-stack-crud-operations-example 9/28
3/7/22, 3:48 PM MERN Stack CRUD Operations
https://www.dotnettricks.com/learn/react/mern-stack-crud-operations-example 10/28
3/7/22, 3:48 PM MERN Stack CRUD Operations
https://www.dotnettricks.com/learn/react/mern-stack-crud-operations-example 11/28
3/7/22, 3:48 PM MERN Stack CRUD Operations
https://www.dotnettricks.com/learn/react/mern-stack-crud-operations-example 12/28
3/7/22, 3:48 PM MERN Stack CRUD Operations
https://www.dotnettricks.com/learn/react/mern-stack-crud-operations-example 13/28
3/7/22, 3:48 PM MERN Stack CRUD Operations
Front-end Project
So far, we have completed our back-end implementation, to manipulate with the employee data, we need to use the
different API's into our react project.For User Interface, we are going to use different component of bootstrap using
package react-bootstrap, and few components we have used in this application are listed below.
Navbar
Nav
Table
Button
So these are some primary components we have used to design our user interface.
Now create a new folder named Components inside /src directory and create a new file named Header.js.
Header.js
import '../index.css';
render() {
return (
<div>
<Navbar>
<Navbar.Header>
<Navbar.Brand>
</Navbar.Brand>
</Navbar.Header>
<Nav>
<NavItem href="javascript:void(0)">
<Link to="/">Home</Link>
</NavItem>
<NavItem href="javascript:void(0)">
</NavItem>
</Nav>
</Navbar>
</div>
);
https://www.dotnettricks.com/learn/react/mern-stack-crud-operations-example 14/28
3/7/22, 3:48 PM MERN Stack CRUD Operations
This file will act as a reusable navigation bar for the whole application. Now create new file Main.js, in which we will
implement routing part of our MERN stack app.
Main.js
render() {
return (
<main>
<Switch>
</Switch>
</main>
);
Next step is to include both these files and include in our main component named App.js.
/src/App.js
render() {
return (
<div>
<Header />
<Main />
</div>
);
https://www.dotnettricks.com/learn/react/mern-stack-crud-operations-example 15/28
3/7/22, 3:48 PM MERN Stack CRUD Operations
To finalize our routing functionality, we need to use BrowserRouter selector which is part of react-router-dom package,
and basically used to allow application to switch from one page to another.
/src/index.js
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>, document.getElementById('root'));
registerServiceWorker();
Service File
In this article, for delete request I am using service file to call delete API from the back-end, still, we can call API directly
from the component, create a new file named Services.js.
/src/Components/Services.js
class EmployeeService {
deleteEmployee(id) {
axios.get('http://localhost:4000/employees/deleteEmployee/' + id)
.then(() => {
})
.catch((error) => {
console.log(error)
})
CRUD Pages
Create Page
To create a new employee, we need to have one component where we can implement the form related functionality,
for that I would suggest you create a new file named AddEmployee.js.
/src/Components/AddEmployee.js
https://www.dotnettricks.com/learn/react/mern-stack-crud-operations-example 16/28
3/7/22, 3:48 PM MERN Stack CRUD Operations
const customStyle = {
width: '300px',
constructor(props) {
super(props);
this.state = {
firstName: '',
lastName: '',
email: '',
phone: ''
event.preventDefault();
axios.post('http://localhost:4000/employees/addEmployee', {
firstName: firstName,
lastName: lastName,
email: email,
phone: phone,
})
.then((response) => {
console.log(response);
this.props.history.push('/');
})
.catch((error) => {
console.log(error);
});
render() {
return (
<div className="container">
<label>
First Name
<input
name="firstName"
type="text"
https://www.dotnettricks.com/learn/react/mern-stack-crud-operations-example 17/28
3/7/22, 3:48 PM MERN Stack CRUD Operations
value={this.state.firstName}
onChange={this.handleChange}
className="form-control"
/>
</label>
<br />
<label>
Last Name
<input
name="lastName"
type="text"
value={this.state.lastName}
onChange={this.handleChange}
className="form-control"
/>
</label>
<br />
<label>
<input
name="email"
type="text"
value={this.state.email}
onChange={this.handleChange}
className="form-control"
/>
</label>
<br />
<label>
Phone No
<input
name="phone"
type="text"
value={this.state.phone}
onChange={this.handleChange}
className="form-control"
/>
</label>
<br />
<input
type="submit"
value="submit"
className="btn btn-primary"
/>
</form>
</div>
);
https://www.dotnettricks.com/learn/react/mern-stack-crud-operations-example 18/28
3/7/22, 3:48 PM MERN Stack CRUD Operations
As you can see into the above code snippet, I have implemented a few things like.
Read Page
In this page, we are going to list down the entire employees, and also enable the user to edit and delete specific
records by providing actions buttons. For that create a new file named ListEmployee.js.
/src/Components/ListEmployee.js
https://www.dotnettricks.com/learn/react/mern-stack-crud-operations-example 19/28
3/7/22, 3:48 PM MERN Stack CRUD Operations
import '../index.css';
var divStyle = {
};
constructor(props) {
super(props);
this.state = {
employees: []
this.deleteEmployee = this.deleteEmployee.bind(this);
componentDidMount = () => {
this.getEmployeeList();
getEmployeeList() {
axios.get('http://localhost:4000/employees')
.then((response) => {
console.log(response);
this.setState({
employees: response.data
});
})
.catch((error) => {
console.log(error);
})
deleteEmployee(empid) {
this.employeeService.deleteEmployee(empid);
this.getEmployeeList();
render() {
<div style={divStyle}>
https://www.dotnettricks.com/learn/react/mern-stack-crud-operations-example 20/28
3/7/22, 3:48 PM MERN Stack CRUD Operations
<Table responsive>
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Phone</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
return (
<tr key={i}>
<td>{i}</td>
<td>{employee.firstName}</td>
<td>{employee.lastName}</td>
<td>{employee.email}</td>
<td>{employee.phone}</td>
<td>
</td>
<td>
</td>
</tr>
})
</tbody>
</Table>
</div>
);
Here in this main page of the application, we are going to list down the entire employees using bootstrap table and
also providing two different action buttons which enable the user to manipulate employee data.
Update Page
When the user wants to edit the employee, at that time they will be navigated to the edit page where the details of the
existing employee will be filled automatically into the form and the user will be able to update it.
/src/Components/EditEmployee.js
https://www.dotnettricks.com/learn/react/mern-stack-crud-operations-example 21/28
3/7/22, 3:48 PM MERN Stack CRUD Operations
const customStyle = {
width: '300px',
constructor(props) {
super(props);
this.state = {
firstName: '',
lastName: '',
email: '',
phone: ''
componentDidMount = () => {
this.getEmployeeById();
getEmployeeById() {
axios.get('http://localhost:4000/employees/editEmployee/' + this.props.match.params.id)
.then((response) => {
this.setState({
firstName: response.data.firstName,
lastName: response.data.lastName,
email: response.data.email,
phone: response.data.phone
});
})
.catch((error) => {
console.log(error);
})
event.preventDefault();
axios.post('http://localhost:4000/employees/updateEmployee/' + this.props.match.params.id, {
firstName: firstName,
lastName: lastName,
email: email,
https://www.dotnettricks.com/learn/react/mern-stack-crud-operations-example 22/28
3/7/22, 3:48 PM MERN Stack CRUD Operations
phone: phone,
})
.then((response) => {
console.log(response);
this.props.history.push('/');
})
.catch((error) => {
console.log(error);
});
render() {
return (
<div className="container">
<label>
First Name
<input
name="firstName"
type="text"
value={this.state.firstName}
onChange={this.handleChange}
className="form-control"
/>
</label>
<br />
<label>
Last Name
<input
name="lastName"
type="text"
value={this.state.lastName}
onChange={this.handleChange}
className="form-control"
/>
</label>
<br />
<label>
<input
name="email"
type="text"
value={this.state.email}
onChange={this.handleChange}
className="form-control"
/>
</label>
<br />
<label>
Phone No
<input
https://www.dotnettricks.com/learn/react/mern-stack-crud-operations-example 23/28
3/7/22, 3:48 PM MERN Stack CRUD Operations
name="phone"
type="text"
value={this.state.phone}
onChange={this.handleChange}
className="form-control"
/>
</label>
<br />
<input
type="submit"
value="submit"
className="btn btn-primary"
/>
</form>
</div>
);
Filling the form data as per the details based on the API call
Submit the updated data when the user submit the form
Now our CRUD related files are created and also implemented API calls, the next step is to add CDN to the root
HTML file.
As we have discussed previously that we are using different components of react-bootstrap, so for that we need to add
CDN file in a root HTML file like this.
/public/index.html
https://www.dotnettricks.com/learn/react/mern-stack-crud-operations-example 24/28
3/7/22, 3:48 PM MERN Stack CRUD Operations
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
crossorigin="anonymous">
crossorigin="anonymous">
<title>React App</title>
</head>
<body>
<noscript>
</noscript>
<div id="root"></div>
</body>
</html>
In visual studio code PowerShell or command prompt, write below command to run front-end.
Npm start
To run the server, we need to change the directory and execute the below command.
Cd Server Node server.js
How It Works
Create Operation
Click on Add New Employee link and add form details.
https://www.dotnettricks.com/learn/react/mern-stack-crud-operations-example 25/28
3/7/22, 3:48 PM MERN Stack CRUD Operations
Read Operation
By clicking on the Home button, you will be redirected to List page of the employees.
Edit/Update Operation
Modify the data and click on submit button to update employee data.
https://www.dotnettricks.com/learn/react/mern-stack-crud-operations-example 26/28
3/7/22, 3:48 PM MERN Stack CRUD Operations
Delete Operation
Click on delete action button to delete an employee.
Important Note
We are done with the CRUD operations using MERN stack, but still few things are missing and you can enhance it.
Summary
At the end, you have done MERN stack CRUD operation with different JavaScript technologies like MongoDB,
ExpressJs, React and NodeJs, By using MERN stack we can create high performance, scalable and robust application
using different JavaScript-based technologies, I would recommend you to download the source code and play around
https://www.dotnettricks.com/learn/react/mern-stack-crud-operations-example 27/28
3/7/22, 3:48 PM MERN Stack CRUD Operations
that and try to implement separate demo by your own. Thanks for reading.
Share Article
https://www.dotnettricks.com/learn/react/mern-stack-crud-operations-example 28/28