MERN Stack CRUD Operations
MERN Stack CRUD Operations
First of all, we will work on the frontend part of our application using React.js.
Create React Application and installing modules
Step 1: Let’s start building the Front-end part with React. To create a new
React App, enter the following code into terminal and hit enter.
cd mern-stack-crud
Step 3: To run the React App, run the following command:
npm start
This command opens the React App to the browser on the following
URL: http://localhost:3000/
Step 4: To build the React App we need to install some external modules.
// CreateStudent Component
const CreateStudent = () => {
const [formValues, setFormValues] =
useState({ name: '', email: '', rollno: '' })
// onSubmit handler
const onSubmit = studentObject => {
axios.post(
'http://localhost:4000/students/create-student',
studentObject)
.then(res => {
if (res.status === 200)
alert('Student successfully created')
else
Promise.reject()
})
.catch(err => alert('Something went wrong'))
}
// Return student form
return(
<StudentForm initialValues={formValues}
onSubmit={onSubmit}
enableReinitialize>
Create Student
</StudentForm>
)
}
// Export CreateStudent Component
export default CreateStudent
// EditStudent Component
const EditStudent = (props) => {
const [formValues, setFormValues] = useState({
name: "",
email: "",
rollno: "",
});
//onSubmit handler
const onSubmit = (studentObject) => {
axios
.put(
"http://localhost:4000/students/update-student/ " +
props.match.params.id,
studentObject
)
.then((res) => {
if (res.status === 200) {
alert("Student successfully updated");
props.history.push("/student-list");
} else Promise.reject();
})
.catch((err) => alert("Something went wrong"));
};
return (
<div className="table-wrapper">
<Table striped bordered hover>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Roll No</th>
<th>Action</th>
</tr>
</thead>
<tbody>{DataTable()}</tbody>
</Table>
</div>
);
};
export default StudentList;
axios
.delete(
.then((res) => {
window.location.reload();
} else Promise.reject();
})
return (
<tr>
<td>{name}</td>
<td>{email}</td>
<td>{rollno}</td>
<td>
<Link className="edit-link"
to={"/edit-student/" + _id}>
Edit
</Link>
<Button onClick={deleteStudent}
size="sm" variant="danger">
Delete
</Button>
</td>
</tr>
);
};
Step 11: Edit App.js: Finally, include the menu to make routing in
our MERN Stack CRUD app. Go to src/App.js and write the
following code.
// Import React
import React from "react";
// Import Bootstrap
import { Nav, Navbar, Container, Row, Col }
from "react-bootstrap";
import "bootstrap/dist/css/bootstrap.css";
// Import Custom CSS
import "./App.css";
// App Component
const App = () => {
return (
<Router>
<div className="App">
<header className="App-header">
<Navbar bg="dark" variant="dark">
<Container>
<Navbar.Brand>
<Link to={"/create-student"}
className="nav-link">
React MERN Stack App
</Link>
</Navbar.Brand>
<Nav className="justify-content-end">
<Nav>
<Link to={"/create-student"}
className="nav-link">
Create Student
</Link>
</Nav>
<Nav>
<Link to={"/student-list"}
className="nav-link">
Student List
</Link>
</Nav>
</Nav>
</Container>
</Navbar>
</header>
<Container>
<Row>
<Col md={12}>
<div className="wrapper">
<Switch>
<Route exact path="/"
component={CreateStudent} />
<Route path="/create-student"
component={CreateStudent} />
<Route path="/edit-student/:id"
component={EditStudent} />
<Route path="/student-list"
component={StudentList} />
</Switch>
</div>
</Col>
</Row>
</Container>
</div>
</Router>
);
};
body h3 {
margin-bottom: 25px;
}
.navbar-brand a {
color: #ffffff;
}
.form-wrapper,
.table-wrapper {
max-width: 500px;
margin: 0 auto;
}
.table-wrapper {
max-width: 700px;
}
.edit-link {
padding: 7px 10px;
font-size: 0.875rem;
line-height: normal;
border-radius: 0.2rem;
color: #fff;
background-color: #28a745;
border-color: #28a745;
margin-right: 10px;
position: relative;
top: 1px;
}
.edit-link:hover {
text-decoration: none;
color: #ffffff;
}
/* Firefox */
input[type=number] {
-moz-appearance: textfield;
}
Step to run the application: Open the terminal and type the following
command.
npm start
Now we will work on the backend part of our application. We will create a
folder inside our mern-stack-crud to manage the server services such as
database, models, schema, routes and APIs, name this folder backend.
Step 1: Run command to create backend folder for server and get inside of
it.
npm init -y
Go to backend/package.json file will look like the following. Replace
the test property like:
Npm I -D nodemon
};
// Student Model
let studentSchema = require("../models/Student");
// CREATE Student
router.post("/create-student", (req, res, next) => {
studentSchema.create(req.body, (error, data) => {
if (error) {
return next(error);
} else {
console.log(data);
res.json(data);
}
});
});
// READ Students
router.get("/", (req, res) => {
studentSchema.find((error, data) => {
if (error) {
return next(error);
} else {
res.json(data);
}
});
});
// UPDATE student
router
.route("/update-student/:id")
// Get Single Student
.get((req, res) => {
studentSchema.findById(
req.params.id, (error, data) => {
if (error) {
return next(error);
} else {
res.json(data);
}
});
})
// Delete Student
router.delete("/delete-student/:id",
(req, res, next) => {
studentSchema.findByIdAndRemove(
req.params.id, (error, data) => {
if (error) {
return next(error);
} else {
res.status(200).json({
msg: data,
});
}
});
});
module.exports = router;
Step 7: Configure server.js – We have almost created everything
for our mern-stack-crud app. Now, create the server.js file in the
root of the backend folder. Go to backend/server.js and write the
following code.
let express = require('express');
let mongoose = require('mongoose');
let cors = require('cors');
let bodyParser = require('body-parser');
let dbConfig = require('./database/db');
// Express Route
const studentRoute = require('../backend/routes/student.route')
// PORT
const port = process.env.PORT || 4000;
const server = app.listen(port, () => {
console.log('Connected to port ' + port)
})
// 404 Error
app.use((req, res, next) => {
res.status(404).send('Error 404!')
});