MERN Stack CRUD Example (2024) (2024)
What is MERN stack?
MERN stands for MongoDB, Express, React, Node, the four key technologies which create the stack.
- MongoDB - document database
- Express(.js) - Node.js web framework
- React(.js) - a client-side JavaScript framework
- Node(.js) - the premier JavaScript web server
React.js + Node.js + Express + MongoDB example: MERN stack Example
In this tutorial, we will create a CRUD application using the MERN stack (MongoDB + Express + React.js + Node.js).
You can can get git source code at the end of this tutorial.
For REST APIs, the back-end server uses Node.js + Express, while the front-end is a React client with React Router, Axios, and Bootstrap with below rest api's.
POST
- Create Employee RecordGET
- List all employeesGET
- Get employees by it's idPUT
- Update/Edit selected employee detailsDELETE
- Remove selected employee recordDELETE
- RemoveAll employees.
What is Express web framework?
Express is a popular open-source node web framework written in JavaScript and running on the Node.js environment.
Express Model View Controller (MVC) flow:
What is Node?
Node (or Node.js) is an open-source, cross-platform runtime environment that allows JavaScript developers to create a variety of server-side tools and apps. The runtime is designed to be used outside of a browser (i.e. running directly on a computer or server OS).
It has several benefits:
- The node package manager (NPM) gives access to hundreds of thousands of reusable packages.
- Node.js is a portable programming language. Microsoft Windows, macOS, Linux, Solaris, FreeBSD, OpenBSD, WebOS, and NonStop OS are all supported.
- Excellent performance! Node was created with the goal of increasing performance and scalability in web applications.
What is Mongoose used for?
Mongoose is a MongoDB and Node. js-based Object Data Modeling (ODM) library. It keeps track of data relationships, does schema validation, and converts code objects into MongoDB representations.
Express apps can use any database that Node supports. There are several popular choices, including PostgreSQL, MySQL, Redis, SQLite, and MongoDB.
You can refer how to Install MongoDB on Windows and how to access.
React.js + Node.js + Express + MongoDB Example Implementation
Create Express Crud Project
Create Express application skeleton instantly by using the express-generator
application generator tool using below commands:
npm install -g express-generator
express
Now install dependencies.
npm install
Install Mongoose dependency
Mongoose is a MongoDB dependency that maps a document into a JS Object containing all of its data.
npm i mongoose
Project Structure
According to the project's use case or requirements, we can create files and folders.
Checkout our related posts :
Add MongoDB connection details
Create the new folder config
and new file
database-config.js
.
const mongoose = require('mongoose');
mongoose.set("strictQuery", false);
const db_url = 'mongodb://127.0.0.1:27017/TechGeekNextDB';
const connection = () => {
mongoose.connect(db_url, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(()=>console.log('Database connected!'))
.catch(e=>console.log(e));
};
module.exports = connection;
Test MongoDB Connection
Start the express mongodb application by using the npm start
command after providing
the MongoDB
connection
information. If everything goes smoothly, carry on with the rest endpoints;
Express Crud Dependencies
In Express, all of the necessary dependencies are listed in the package.json
file.
It
contains scripts to start, build, test and eject the Express JS application.
{
"name": "express-crud-mongo",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"body-parser": "^1.18.3",
"cookie-parser": "~1.4.4",
"cors": "^2.8.5",
"debug": "~2.6.9",
"express": "~4.16.1",
"http-errors": "~1.6.3",
"jade": "~1.11.0",
"mongoose": "^6.9.0",
"morgan": "~1.9.1"
}
}
Change Default Node js Port as per requirement
From the generated bin/www
file, change the default port from 3000
to
8080
.
Express MongoDB CRUD App - App component
- The App component (
App.js
) is the application's root container. - Default Code base with error handling will be generated by the express application generator tool.
- Change the code for
usersRouter
as given below:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const connection = require('./config/database-config');
const cors = require('cors');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/employee');
var app = express();
app.disable('etag');
app.use(cors({
origin: '*'
}));
connection();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Express MongoDB CRUD Example - Create Model
Create a Model to outline the structure of our employee database. Create the folder
model
and inside create the file employee.js
to define the structure of
employee document to map with database.
const mongoose = require('mongoose');
const EmployeeSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
role: {
type: String,
required: true
}
});
module.exports = mongoose.model('employee', EmployeeSchema);
Express MongoDB CRUD Example - Create Route rest endpoints
- Create the page
employee.js
underroutes
folder. - Create CRUD rest endpoints.
var express = require('express');
const connection = require('../config/database-config');
const employee = require('../models/employee');
var router = express.Router();
/* Add new employee*/
router.post('/employee', async (req, resp, next) => {
const { name, role } = req.body;
try {
const newEmployee = new employee({
name: name,
role: role
});
const savedEmployee = await newEmployee.save();
resp.json(savedEmployee);
} catch (error) {
next(error);
}
});
/* GET all employees listing. */
router.get('/employees', async (req, resp, next) => {
try {
const employees = await employee.find();
var records = [];
employees.forEach(emp => {
if (emp) {
const empsRecord =
{
id: emp._id,
name: emp.name,
role: emp.role
}
records.push(empsRecord);
}
});
resp.json(records);
} catch (error) {
next(error);
}
});
/* Get employee based on id*/
router.get('/employee/:id', async (req, resp, next) => {
try {
const emp = await employee.findById(req.params.id);
resp.json(
{
id: emp._id,
name: emp.name,
role: emp.role
}
);
} catch (error) {
next(error);
}
});
/* Edit existing employee based on id*/
router.put('/employee/:id', async (req, resp, next) => {
try {
const requestBody = { name: req.body.name, role: req.body.role };
let emp_rec = await employee.findById(req.params.id);
if (!emp_rec)
return res.status(404).json({ msg: 'Employee record not found' });
const updatedEmp = await employee.findByIdAndUpdate(
req.params.id, requestBody, { new: true });
resp.json(updatedEmp);
} catch (error) {
next(error);
}
});
/* Delete employee based on id*/
router.delete('/employee/:id', async (req, resp, next) => {
try {
const emp = await employee.findByIdAndDelete(req.params.id);
resp.send(`Employee ${emp.name} record deleted!`)
} catch (error) {
next(error);
}
});
/* Delete all employees*/
router.delete('/employees', async (req, resp, next) => {
try {
const emp = await employee.remove({});
resp.send(`All employee records has been deleted!`)
} catch (error) {
next(error);
}
});
module.exports = router;
Create React JS Application
Refer ReactJS Node.js CRUD Example for React js front end implementation with source code.
Test React.js + Node.js + Express + MongoDB - MERN stack CRUD Example
- Run the express js mongodb application by using below command:
npm start
- The application will open in browser at our configured port http://localhost:8080/ url.
- Start the ReactJS CRUD Application.
Add Employee
Click on Create New Employee and provide employee name and role.List Employees
On the Home page, you will see all created employees with action to edit and delete.Edit Employee
Click on Edit icon from the employee table to edit the record from the Edit page.Remove Employee
Click on Remove icon from the employee table to remove the record.Remove All Employees
Click on Remove All button to remove all the employee records from the database table.
Download Source Code
The full source code for this article can be found on below.Download it here - Express MongoDB Crud Example