MERN STACK CRUD tutorial with examples

 The MERN stack is another popular full-stack web development framework consisting of MongoDB, Express, React, and Node.js. This stack allows you to build dynamic, single-page applications (SPAs) using JavaScript for both the front-end and back-end.

In this tutorial, we’ll build a simple MERN stack CRUD (Create, Read, Update, Delete) application that allows users to manage a list of tasks.


Prerequisites:

  1. Node.js and npm installed on your machine.
  2. React and Node.js basics.
  3. MongoDB installed locally or using a service like MongoDB Atlas.
  4. Basic understanding of JavaScript, React, and Express.

Step 1: Setting Up the Backend (Node.js + Express + MongoDB)

1.1. Initialize a new Node.js Project

First, create a new directory for your MERN stack app.

bash
mkdir mern-crud-app cd mern-crud-app

Initialize a Node.js project by running:

bash
npm init -y

1.2. Install Dependencies

We need the following dependencies:

  • express: For creating the server.
  • mongoose: For MongoDB object modeling.
  • cors: To allow cross-origin requests between client and server.
  • dotenv: To manage environment variables securely.
  • body-parser: To parse incoming request bodies.

Run the following command to install the necessary packages:

bash
npm install express mongoose cors body-parser dotenv

1.3. Create the Backend Server

Create an index.js file in the root of your project. This file will set up the Express server, MongoDB connection, and define routes for CRUD operations.

javascript
// index.js const express = require('express'); const mongoose = require('mongoose'); const bodyParser = require('body-parser'); const cors = require('cors'); const dotenv = require('dotenv'); dotenv.config(); const app = express(); const port = process.env.PORT || 5000; // Middleware app.use(cors()); app.use(bodyParser.json()); // MongoDB connection mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/merncrud', { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('Connected to MongoDB')) .catch(err => console.log('MongoDB connection error:', err)); // Task Model const taskSchema = new mongoose.Schema({ name: String, completed: { type: Boolean, default: false } }); const Task = mongoose.model('Task', taskSchema); // Routes // Get all tasks app.get('/tasks', async (req, res) => { try { const tasks = await Task.find(); res.json(tasks); } catch (err) { res.status(500).send('Error fetching tasks'); } }); // Add a task app.post('/tasks', async (req, res) => { const { name } = req.body; const task = new Task({ name }); try { await task.save(); res.status(201).json(task); } catch (err) { res.status(400).send('Error saving task'); } }); // Update a task app.put('/tasks/:id', async (req, res) => { const { id } = req.params; const { name, completed } = req.body; try { const task = await Task.findByIdAndUpdate(id, { name, completed }, { new: true }); res.json(task); } catch (err) { res.status(500).send('Error updating task'); } }); // Delete a task app.delete('/tasks/:id', async (req, res) => { const { id } = req.params; try { await Task.findByIdAndDelete(id); res.json({ message: 'Task deleted' }); } catch (err) { res.status(500).send('Error deleting task'); } }); // Start server app.listen(port, () => { console.log(`Server running on http://localhost:${port}`); });

1.4. Create .env File for Environment Variables

In the root of your project, create a .env file to store your MongoDB URI securely.

bash
MONGODB_URI=mongodb://localhost:27017/merncrud

Note: If you're using MongoDB Atlas, replace the MONGODB_URI value with your Atlas connection string.

1.5. Run the Backend Server

To start the server, run the following command:

bash
node index.js

The server will be running on http://localhost:5000.


Step 2: Setting Up the Frontend (React)

2.1. Create a React App

Navigate back to your root directory and create a React app in the client folder using the Create React App tool.

bash
npx create-react-app client cd client

2.2. Install Axios for HTTP Requests

Axios is a promise-based HTTP client that we will use to make API requests to the backend.

bash
npm install axios

2.3. Create a Task Component to Display and Manage Tasks

In the src folder, create a new component called TaskList.js.

javascript
// src/TaskList.js import React, { useState, useEffect } from 'react'; import axios from 'axios'; function TaskList() { const [tasks, setTasks] = useState([]); const [newTask, setNewTask] = useState(''); // Fetch tasks from the backend useEffect(() => { axios.get('http://localhost:5000/tasks') .then(response => setTasks(response.data)) .catch(err => console.log(err)); }, [tasks]); // Handle adding a new task const addTask = () => { if (newTask) { axios.post('http://localhost:5000/tasks', { name: newTask }) .then(response => setNewTask('')) // Clear input after adding task .catch(err => console.log(err)); } }; // Handle updating a task const updateTask = (task) => { axios.put(`http://localhost:5000/tasks/${task._id}`, { name: task.name, completed: !task.completed }).catch(err => console.log(err)); }; // Handle deleting a task const deleteTask = (id) => { axios.delete(`http://localhost:5000/tasks/${id}`) .catch(err => console.log(err)); }; return ( <div> <h1>Task List</h1> <input type="text" value={newTask} onChange={e => setNewTask(e.target.value)} placeholder="New task" /> <button onClick={addTask}>Add Task</button> <ul> {tasks.map(task => ( <li key={task._id}> <span style={{ textDecoration: task.completed ? 'line-through' : 'none' }} onClick={() => updateTask(task)} > {task.name} </span> <button onClick={() => deleteTask(task._id)}>Delete</button> </li> ))} </ul> </div> ); } export default TaskList;

2.4. Set Up React App to Use the Task Component

In src/App.js, import and use the TaskList component.

javascript
// src/App.js import React from 'react'; import './App.css'; import TaskList from './TaskList'; function App() { return ( <div className="App"> <TaskList /> </div> ); } export default App;

2.5. Running the React Frontend

To run the React app, use the following command in the client folder:

bash
npm start

The React app will be running on http://localhost:3000.


Step 3: Testing the MERN CRUD Application

  1. Create a Task: Enter a task name and click Add Task. The task will be added to the backend and appear in the task list.
  2. Update a Task: Click on a task name to toggle its completed status (cross out the name if completed).
  3. Delete a Task: Click the Delete button next to a task to delete it from both the frontend and backend.
  4. View Tasks: All tasks will be displayed in the task list. They will be dynamically fetched from the backend each time the page reloads.

Conclusion

In this tutorial, we built a simple MERN stack CRUD application to manage tasks. We used Node.js and Express for the backend, MongoDB for the database, and React for the frontend.

You can extend this application by adding additional features such as user authentication, task prioritization, due dates, etc. You could also deploy the application using platforms like Heroku or Vercel for the frontend, and MongoDB Atlas for the database.

Comments

Popular posts from this blog

PrimeNG tutorial with examples using frequently used classes

Docker and Kubernetes Tutorials and QnA

Building strong foundational knowledge in frontend development topics