,

Complete guide to performing CRUD operations using MongoDB, Node.js, and Express.js in 2023

Posted by


In this tutorial, we will be learning how to perform CRUD (Create, Read, Update, Delete) operations in a React application using MongoDB as our database, and Node.js with Express.js as our backend server.

To get started, make sure you have Node.js installed on your machine. If not, you can download and install it from the official Node.js website.

Step 1: Setting up the Node.js server

First, create a new directory for your project and navigate into it using the terminal. Then, run the following command to create a new package.json file:

npm init -y

Next, install Express.js and Mongoose (a MongoDB ORM) using the following command:

npm install express mongoose

Create a new file named server.js in your project directory and add the following code to it:

const express = require('express');
const mongoose = require('mongoose');

const app = express();
const port = 3000;

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

You can start your server by running the following command:

node server.js

Step 2: Setting up MongoDB

Next, you need to set up a MongoDB database. You can either use a local MongoDB instance or create a free account on MongoDB Atlas for a cloud-based database.

Once you have set up your MongoDB database, you will need to connect it to your Node.js server. Update your server.js file with the following code to establish a connection to your MongoDB database:

mongoose.connect('mongodb://localhost:27017/reactCrud', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

Replace the MongoDB connection URL with your own database URL if you are using a cloud-based database.

Step 3: Creating the model

Now, let’s create a model for our data in MongoDB. Create a new file named models/item.js and add the following code to define a simple schema for our data:

const mongoose = require('mongoose');

const ItemSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
  },
  description: {
    type: String,
  },
  price: {
    type: Number,
    required: true,
  },
});

const Item = mongoose.model('Item', ItemSchema);

module.exports = Item;

Step 4: Implementing CRUD operations

Now that we have set up the server, connected to the database, and defined our data model, let’s implement the CRUD operations in our server.

Add the following routes to your server.js file to handle the CRUD operations:

const Item = require('./models/item');

app.get('/items', async (req, res) => {
  const items = await Item.find();
  res.json(items);
});

app.post('/items', async (req, res) => {
  const { name, description, price } = req.body;
  const newItem = new Item({ name, description, price });
  await newItem.save();
  res.json({ message: 'Item created successfully' });
});

app.put('/items/:id', async (req, res) => {
  const { name, description, price } = req.body;
  const updatedItem = await Item.findByIdAndUpdate(req.params.id, { name, description, price });
  res.json({ message: 'Item updated successfully' });
});

app.delete('/items/:id', async (req, res) => {
  await Item.findByIdAndDelete(req.params.id);
  res.json({ message: 'Item deleted successfully' });
});

Step 5: Setting up the React frontend

Now that we have our backend server set up, let’s create a React frontend to interact with our API. Create a new React app using Create React App by running the following command in your project directory:

npx create-react-app client

Navigate into the client directory and start the development server by running the following command:

npm start

Step 6: Consuming the API in React

In your React app, you can now make API requests to your backend server to perform CRUD operations.

Create a new component in your React app to display a list of items fetched from your API. You can use the fetch API or a library like Axios to make HTTP requests.

import React, { useState, useEffect } from 'react';

const ItemsList = () => {
  const [items, setItems] = useState([]);

  useEffect(() => {
    fetch('/items')
      .then(res => res.json())
      .then(data => setItems(data));
  }, []);

  return (
    <div>
      <h1>Items List</h1>
      <ul>
        {items.map(item => (
          <li key={item._id}>
            <strong>{item.name}</strong> - ${item.price}
          </li>
        ))}
      </ul>
    </div>
  );
};

export default ItemsList;

You can now import and render the ItemsList component in your App.js file to display the list of items fetched from your API.

That’s it! You have successfully implemented CRUD operations in a React application using MongoDB, Node.js, and Express.js. You can further enhance this application by adding form components to create new items, update existing items, and delete items.

I hope this tutorial was helpful in getting you started with building full-stack applications with React and MongoDB. Happy coding!

0 0 votes
Article Rating

Leave a Reply

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@neelnickkey4865
1 hour ago

Thank you fellow developer … love from India thanks for sharing your knowledge…!!!c

@souravbiswas5388
1 hour ago

aise aur project based learning daalte rahe, bahut help hogi junior dev's ki.

2
0
Would love your thoughts, please comment.x
()
x