shape
shape

Building a Simple CRUD Application with the MERN Stack: A Step-by-Step Guide

  • Home
  • MERN
  • Building a Simple CRUD Application with the MERN Stack: A Step-by-Step Guide

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.

Table of Contents

  1. What is CRUD?
  2. Overview of the MERN Stack
  3. Setting Up the Development Environment
  4. Backend: Building the API with Node.js, Express, and MongoDB
    1. Installing dependencies
    2. Creating the server
    3. Defining API routes
  5. Frontend: Building the User Interface with React
  1. Setting up React
  2. Creating components
  3. Integrating API calls
  1. Testing the CRUD Operations
  2. Deploying the Application
  3. Conclusion

1. What is CRUD?

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.

  • Create: Add new records to the database.
  • Read: Retrieve and display existing records.
  • Update: Modify existing records.
  • Delete: Remove records from the database.

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.


2. Overview of the MERN Stack

The MERN stack consists of the following technologies:

  • MongoDB: A NoSQL database that stores data in flexible, JSON-like documents.
  • Express: A lightweight web framework for Node.js used to build backend services.
  • React: A JavaScript library for building user interfaces, particularly single-page applications (SPA).
  • Node.js: A runtime environment that allows JavaScript to run on the server-side.

Together, these technologies form a full-stack solution for web applications, enabling developers to work with JavaScript across the entire development process.


3. Setting Up the Development Environment

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.


4. Backend: Building the API with Node.js, Express, and MongoDB
Step 1: Installing Dependencies

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-backendcd mern-crud-backend

npm init -y

npm install express mongoose cors dotenv

  • Express: Web framework for Node.js.
  • Mongoose: Object Data Modeling (ODM) library for MongoDB.
  • CORS: Middleware to allow cross-origin requests.
  • dotenv: To manage environment variables.
Step 2: Creating the Server

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}`);

});

Step 3: Defining API Routes

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.


5. Frontend: Building the User Interface with React
Step 1: Setting up React

Create a new React app by running the following commands:

bash

Copy code

npx create-react-app mern-crud-frontendcd mern-crud-frontend

Install Axios for making HTTP requests:

bash

Copy code

npm install axios

Step 2: Creating Components

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;

Step 3: Integrating API Calls

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;


6. Testing the CRUD Operations

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.


7. Deploying the Application

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.


8. Conclusion

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

0
    0
    Your Cart
    Your cart is emptyReturn to shop