Introduction
CRUD stands for Create, Read, Update, and Delete. It is the basic operation of any data-driven web application that involves databases. These four operations for creating and managing databases are essential for any web application that involves relational and NoSQL databases. For building a small blog or complex e-commerce platform, CRUD operation helps to interact with data. In the MERN Stack Framework, CRUD operation is the complete step-by-step guide for building web applications stacks based on Node. The purpose of this tutorial is to explain how CRUD operations form the backbone of dynamic applications in MERN Stack.
Understanding CRUD Operations
CRUD Operation represents the essential elements needed to be performed on data in a database. It helps the user to create new entries, fetch the data from the database, modify or add the data, and also to remove data in a database. The four main operations of data management techniques are as follows:
- Create: Adds new data to the database. For example, a User wants to create a new account on a website platform. It creates a new entry in a database.
- Read: Retrieve any data from the database. For example, the User wants to see the number of orders received from the customer.
- Update: Modify / Update the existing data in a database. For example, the User wants to change the address in the profile information.
- Delete: Remove data from the database. For example, Deleting a user account or post.
Overview of the MERN Stack
The MERN Stack comprises four powerful technologies to create full-stack JavaScript web applications. The four technologies are as follows:
- MongoDB – It is a NoSQL database for storing data using JSON/JavaScript Syntax.
- Express.js – It is the server-side logic backend framework for handling APIs.
- React – It is the frontend library for building interactive user interfaces.
- Node.js – It is the runtime environment that allows JavaScript to run on the server side.
By combining all these four technologies using MERN Stack, developers can create robust and scalable web applications.
Role of CRUD in a MERN Application
CRUD operation is the foundation of data management in the MERN Stack. Each operation supports the seamless communication between the frontend, backend, and database to ensure an interactive user experience. Let’s see how this operation works on the MERN stack.
Frontend (React)
React handles the user interaction using Frontend libraries and sends the user request to the backend for CRUD operation with the help of Rest APIs. Based on the user interaction, CRUD operation will perform the functionality as follows:
- Create: The user fills out a form to enter a new account for signup. Hence React captures user input to create data in MongoDB.
- Read: The user needs to fetch the data such as product lists or order details. React fetches the data from the backend which is accomplished dynamically in React components and displays the data to the user.
- Update: The user submits editable forms to modify existing data such as changing the profile information of an existing user or changing the price of the product by admin.
- Delete: The user submits a button to delete the data from the database such as deleting unwanted comments from the post.
Backend (Express.js/Node.js)
The backend processes the CRUD requests and acts as a bridge between the front end (React) and the database (MongoDB). It accepts incoming API requests from the front end to process and operate the data in the database. Based on the API request from user Interface operation mapping are as follows:
- POST: It adds the data to the database when the user submits a form to add the data.
- GET: It retrieves the data from the database when the user clicks a button to read the data.
- PUT/PATCH: It updates the existing data in the database when the user submits an editable form to modify the data in the database.
- DELETE: It removes the data from the database when the user clicks a button to delete the data.
During CRUD operation, Middleware in Express ensures data validation, authentication, and error Handling. After the interaction with MongoDB, Express.js sends responses back to the React Frontend.
Database (MongoDB)
MongoDB handles the actual data in the database. After the data validation and authentication, MongoDB performs addition, modification, and retrieval of the dataset from the database based on the response from the Backend (Express.js).
- Create: New records are added to the data collection as a new document. MongoDB automatically assigns a new unique ID to each document.
- Read: Queries retrieve specific documents or datasets based on the API response.
- Update: Documents are updated using filters and update operators.
- Delete: Documents matching specific criteria are deleted or removed from the database.
Implementing CRUD Operations in MERN
CRUD operation is the basic fundamental core for interacting with data and managing data in the MERN application. Here is the step-by-step guide for implementing these CRUD operations in MERN Stack.
Create Operation
Adding new records such as user registration or product addition.
Frontend (React): A form is submitted by the user to create a new user profile in the frontend UI. This data is sent to the backend using a POST request.
Code Example: const handleRegistration = async (event) => { event.preventDefault(); const response = await fetch('/api/register', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, userEmail, userPassword }), }); const result = await response.json(); console.log('Registration response:', result); };
Backend (Express.js/Node.js): Define the POST endpoint in Express.js for receiving the data and saving it to the MongoDB.
Code Example: app.post('/api/register', async (req, res) => { const newUser = new User(req.body); // `User` is a predefined Mongoose schema model await newUser.save(); res.status(201).json(newUser); });
Database (MongoDB): MongoDB creates a new document in the corresponding section with the unique ID for each document.
Code Example: db.users.insertOne({ name: "tutedude", email: "tutedude.com", age: 30 });
Read Operation
Retrieve the data from the dataset to display it in the front, such as viewing a post or user profiles.
Frontend (React): The user clicks a button to read the data. React retrieves the data using GET requests and displays it using React components.
Code Example: useEffect(() => { const getPosts = async () => { const res = await fetch('/api/posts'); const fetchedData = await res.json(); setPosts(fetchedData); }; getPosts(); }, []);
Backend (Express.js/Node.js): Define the GET endpoint to retrieve data from the database.
Code Example: app.get('/api/posts', async (req, res) => { const allPosts = await Post.find(); // Retrieve all documents from the Post collection res.status(200).json(allPosts); });
Database (MongoDB): MongoDB retrieves the requested document based on the query.
Code Example: db.users.find({ age: { $gte: 18 } }); // Query to retrieve users who are 18 years old or above
Update Operation
Modify the dataset in the data collection such as changing addresses in the existing user profiles or changing the price value of products.
Frontend (React): The user submits an editable form to update the data. React component sends a PUT/PATCH request to the backend with the updated information.
Code Example: const updateUserData = async (userId, newDetails) => { const res = await fetch(`/api/users/${userId}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(newDetails), }); const result = await res.json(); console.log('Updated user data:', result); };
Backend (Express.js/Node.js): Define the PUT/PATCH endpoint to handle the request.
Code Example: app.put('/api/users/:id', async (req, res) => { const updatedUser = await User.findByIdAndUpdate(req.params.id, req.body, { new: true }); res.status(200).json(updatedUser); });
Database (MongoDB): MongoDB updates the document with the new values.
Code Example: db.users.updateOne({ _id: "tute123" }, { $set: { name: " Tute Dude 2" } });
Delete Operation
Removes the document that matches specific conditions such as deleting a user profile or removing product details.
Frontend (React): The user clicks a button that triggers the DELETE request.
Code Example: const deletePost = async (postId) => { const res = await fetch(`/api/posts/${postId}`, { method: 'DELETE', }); if (res.ok) { console.log('Successfully removed the post'); } };
Backend (Express.js/Node.js): Define the DELETE endpoint to remove the document from the database.
Code Example: app.delete('/api/posts/:id', async (req, res) => { await Post.findByIdAndRemove(req.params.id); res.status(200).json({ message: 'Post successfully deleted' }); });
Database (MongoDB): MongoDB deletes the specified document from the collection.
Code Example: db.users.deleteOne({ _id: "tutedude123" });
Common Challenges in CRUD Operations
CRUD operations in the MERN stack often come with their own set of challenges. Some of the challenges and their remedies are as follows:
- CRUD operations sometimes send asynchronous data to the backend which causes race conditions or improper synchronization of data. Developers need to use Promises or async/await to ensure proper handling of synchronization.
- Frontend and Backend communication may fail due to CORS (Cross Origin Resource Sharing) restrictions on different domains. Express may use Cors middleware to configure the backend.
- Server-side errors are displayed on the front end which is crucial for debugging and user feedback. Developers may use try-catch blocks in asynchronous functions to catch and log errors.
- Complex database queries may lead to slow performance. Proper indexing and Query optimization techniques are used in MongoDB to optimize databases.
Conclusion
CRUD operation is the foundation of interactive web applications, empowering seamless data management and user interaction. The flexibility and efficiency of the MERN Stack for building CRUD-based applications emphasize a comprehensive solution for full-stack development.
Take the next step in your journey! Ready to become a full-stack developer? Join Our MERN Stack Course and start building powerful applications today! From basic knowledge to advanced features, we will guide you on every step. Start building your dream projects Today!
If you found this article useful, bookmark it for future reference or share it you’re your network.