The MERN stack (MongoDB, Express, React, and Node.js) has become a popular choice for full-stack web development because it allows developers to use JavaScript for both frontend and backend development. Building a CRUD (Create, Read, Update, Delete) application is an excellent way to get started with the MERN stack, as it covers the core functionalities of most applications. In this guide, we’ll walk you through building a simple CRUD application using the MERN stack.
CRUD stands for Create, Read, Update, and Delete, which are the four basic operations for interacting with a database. These operations are essential for any web application that involves data storage and retrieval.
In this tutorial, we will build a simple CRUD application that manages a list of items, such as a to-do list or a list of users.
The MERN stack consists of the following technologies:
Together, these technologies form a full-stack solution for web applications, enabling developers to work with JavaScript across the entire development process.
Before we start building our CRUD application, ensure you have the following installed:
To create a new MERN project, you will need two separate directories: one for the backend and one for the frontend.
First, let’s set up the backend by creating a directory for the server and installing the necessary dependencies.
bash
Copy code
mkdir mern-crud-backend
cd mern-crud-backend
npm init -y
npm install express mongoose cors dotenv
Create an index.js
file and set up a basic Express server:
javascript
Copy code
const express =
require(
‘express’);
const mongoose =
require(
‘mongoose’);
const cors =
require(
‘cors’);
const app =
express();
require(
‘dotenv’).
config();
app.
use(
cors());
app.
use(express.
json());
const
PORT = process.
env.
PORT ||
5000;
mongoose.
connect(process.
env.
MONGO_URI, {
useNewUrlParser:
true,
useUnifiedTopology:
true })
.
then(
() =>
console.
log(
‘MongoDB connected’))
.
catch(
err =>
console.
log(err));
app.
listen(
PORT,
() => {
console.
log(
`Server is running on port ${PORT}`);
});
Next, we need to define the routes for our CRUD operations. In this case, we’ll create a simple API for managing items.
javascript
Copy code
const express =
require(
‘express’);
const router = express.
Router();
const
Item =
require(
‘./models/Item’);
// Assuming Item is a Mongoose model
// Create
router.
post(
‘/items’,
async (req, res) => {
const newItem =
new
Item(req.
body);
try {
const savedItem =
await newItem.
save();
res.
json(savedItem);
}
catch (err) {
res.
status(
400).
json({
message: err.
message });
}
});
// Read
router.
get(
‘/items’,
async (req, res) => {
try {
const items =
await
Item.
find();
res.
json(items);
}
catch (err) {
res.
status(
400).
json({
message: err.
message });
}
});
// Update
router.
put(
‘/items/:id’,
async (req, res) => {
try {
const updatedItem =
await
Item.
findByIdAndUpdate(req.
params.
id, req.
body, {
new:
true });
res.
json(updatedItem);
}
catch (err) {
res.
status(
400).
json({
message: err.
message });
}
});
// Delete
router.
delete(
‘/items/:id’,
async (req, res) => {
try {
await
Item.
findByIdAndDelete(req.
params.
id);
res.
json({
message:
‘Item deleted’ });
}
catch (err) {
res.
status(
400).
json({
message: err.
message });
}
});
module.
exports = router;
In the next section, we’ll create the frontend using React.
Create a new React app by running the following commands:
bash
Copy code
npx create-react-app mern-crud-frontend
cd mern-crud-frontend
Install Axios for making HTTP requests:
bash
Copy code
npm install axios
For the frontend, we will create components for adding, listing, updating, and deleting items. Create a simple ItemList
and AddItem
component.
javascript
Copy code
import
React, { useState, useEffect }
from
‘react’;
import axios
from
‘axios’;
const
ItemList = () => {
const [items, setItems] =
useState([]);
useEffect(
() => {
axios.
get(
‘http://localhost:5000/items’)
.
then(
response =>
setItems(response.
data))
.
catch(
error =>
console.
error(
‘Error fetching data:’, error));
}, []);
return (
<div>
<h2>Items List</h2>
<ul>
{items.map(item => (
<li key={item._id}>
{item.name}
{/* Add edit and delete functionality here */}
</li>
))}
</ul>
</div>
);
};
export
default
ItemList;
You’ll need to add Axios calls for creating, updating, and deleting items. Here’s an example of how to create a new item:
javascript
Copy code
const
AddItem = () => {
const [name, setName] =
useState(
”);
const
handleSubmit = (
e) => {
e.
preventDefault();
axios.
post(
‘http://localhost:5000/items’, { name })
.
then(
response =>
console.
log(response.
data))
.
catch(
error =>
console.
error(
‘Error adding item:’, error));
};
return (
<form onSubmit={handleSubmit}>
<input
type=”text”
value={name}
onChange={(e) => setName(e.target.value)}
placeholder=”Item name”
/>
<button type=”submit”>Add Item</button>
</form>
);
};
export
default
AddItem;
Once both your backend and frontend are running, you can test the application by adding, listing, updating, and deleting items. The frontend will send requests to the backend, which interacts with the MongoDB database to perform CRUD operations.
To deploy the application, you can use platforms like Heroku (for the backend) and Netlify (for the frontend). Make sure to configure environment variables like your MongoDB URI in production.
Building a CRUD application with the MERN stack is a great way to learn full-stack development. You’ve now created a simple app that allows users to create, read, update, and delete items. From here, you can enhance the app by adding more features, such as authentication, form validation, and error handling.
By mastering the MERN stack, you’ll have a powerful toolset for building modern web applications that are scalable and efficient.
Comments are closed