When it comes to developing web applications, performing CRUD operations is a fundamental requirement. CRUD, an acronym for create, read, update, and delete, encompasses the elementary actions used to manipulate data. In this blog, we will explore how to build a CRUD application using Node.js, a popular server-side JavaScript runtime, and MongoDB, a NoSQL database.
Prior to proceeding, please ensure that you have the following prerequisites installed:
➡️ Node.js: You can download and install it from the official Node.js website.
➡️ MongoDB: Install MongoDB Community Edition by following the instructions provided in the official MongoDB documentation.
To get started, open your preferred text editor or integrated development environment (IDE) and follow the steps below:
➡️ To initiate your project, create a fresh directory and access it through the command line interface.
➡️ To initialize a new Node.js project, execute the following command:
npm init -y
This will create a package.json file, which will store the project’s metadata and dependencies.
➡️ To Install the required dependencies: Express and Mongoose. Run the following command:
npm install express mongoose
Express is a popular web application framework for Node.js, while Mongoose is an Object Data Modeling (ODM) library that provides a simple interface for interacting with MongoDB.
Related read: Best Nodejs Frameworks To Use In 2023
Now, let’s set up the server by creating an app.js file in the project directory.
Open the file in your text editor and add the following code for CRUD operation:
const express = require("express"); const mongoose = require("mongoose"); const app = express(); app.use(express.json()); mongoose .connect("mongodb://localhost/blogs") .then(() => { console.log("MongoDB connected successfully!"); }) .catch((err) => { console.log("Error connecting to MongoDB:", err); process.exit(1); // Terminate the application if connection fails }); const blogDataSchema = new mongoose.Schema({ title: String, sub_title: String, post_desc: String, email: String, isPublished: Boolean, blogType: String, }); const BlogData = mongoose.model("BlogData", blogDataSchema); // Create Operation app.post("/addBlog", async (req, res) => { const payload = req.body; try { const blogData = new BlogData(payload); await blogData.validate(); // Validate the data against the schema const savedBlog = await blogData.save(); res.send(savedBlog); } catch (error) { res.status(400).send("Invalid blog data provided!"); } }); // Read Operation - Fetch all blogs app.get("/getBlogs", async (req, res) => { try { const blogData = await BlogData.find(); res.send(blogData); } catch (error) { res.status(500).send("An error occurred while fetching the blogs."); } }); // Read Operation - Fetch blog by ID app.get("/getBlogById/:id", async (req, res) => { const blogId = req.params.id; try { const blogData = await BlogData.findById(blogId); if (!blogData) { return res.status(400).send("Invalid blogId provided!"); } res.send(blogData); } catch (error) { res.status(500).send("An error occurred while fetching the blog."); } }); // Update Operation app.put("/updateBlog/:id", async (req, res) => { const blogId = req.params.id; const payload = req.body; try { const updatedBlog = await BlogData.findByIdAndUpdate(blogId, payload, { new: true }); if (!updatedBlog) { return res.status(400).send("Invalid blogId provided!"); } res.send(updatedBlog); } catch (error) { res.status(500).send("An error occurred while updating the blog."); } }); // Delete Operation app.delete("/deleteBlog/:id", async (req, res) => { const blogId = req.params.id; try { const deletedBlog = await BlogData.findByIdAndDelete(blogId); if (!deletedBlog) { return res.status(400).send("Invalid blogId provided!"); } res.send("Blog deleted successfully"); } catch (error) { res.status(500).send("An error occurred while deleting the blog."); } }); app.listen(9000, () => { console.log("App listening on port 9000"); });
The create operation is responsible for adding new blog entries to our application. When a user submits a new blog, the data is sent to the server via a POST request. The server extracts the payload from the request body and validates it against the defined schema. If the data is valid, a new instance of the BlogData model is created and saved to the MongoDB database using the save() method. The saved blog entry is then sent back as a response to the client.
There are two read operations implemented in our CRUD application: fetching all blogs and fetching a blog by its ID.
1. The “fetch all blogs” operation is triggered when a user sends a GET request to the /getBlogs endpoint. The server uses the find() method of the BlogData model to retrieve all documents from the MongoDB collection. The retrieved blog data is then sent back as a response.
2. The “fetch blog by ID” operation allows users to retrieve a specific blog entry based on its unique ID. When a user sends a GET request to the /getBlogById/:id endpoint, the server extracts the blog ID from the URL parameter.
It then uses the findById() method of the BlogData model to search for a blog entry with the provided ID. If a matching blog is found, it is sent back as a response. Otherwise, a 400 status code is returned along with an error message.
The update operation enables users to modify an existing blog entry. To update a blog, the client sends a PUT request to the /updateBlog/:id endpoint, providing the ID of the blog to be updated and the updated data in the request body. The server uses the findByIdAndUpdate() method of the BlogData model to find the blog entry by its ID and update it with the new data.
If the blog is successfully updated, the updated blog entry is sent back as a response. If no blog is found with the provided ID, a 400 status code is returned along with an error message.
The delete operation allows users to remove a blog entry from the application. To delete a blog, the user sends a DELETE request to the /deleteBlog/:id endpoint, including the ID of the blog to be deleted in the URL parameter.
The server uses the findByIdAndDelete() method of the BlogData model to locate the blog entry with the provided ID and delete it from the database. If the deletion is successful, a success message is sent back as a response. If no blog is found with the provided ID, a 400 status code is returned along with an error message.
These four CRUD operations provide the basic functionalities necessary to manage blog entries in our Node.js application. By implementing these operations, we enable users to create, read, update, and delete blogs, allowing for a dynamic and interactive blogging experience.
In this blog, we have learned how to build a CRUD application using Node.js and MongoDB. We set up the server, defined the database schema using Mongoose, and implemented the CRUD operations. With this knowledge, you can create, read, update, and delete blog data in your application.
Remember that this is a basic example, and in a real-world scenario, you might need to handle authentication, implement additional validation, and optimize the code for performance. Nonetheless, this provides a solid foundation to build upon and expand your application’s functionality.
Nadeem is a front-end developer with 1.5+ years of experience. He has experience in web technologies like React.js, Redux, and UI frameworks. His expertise in building interactive and responsive web applications, creating reusable components, and writing efficient, optimized, and DRY code. He enjoys learning about new technologies.
How to Effectively Hire and Manage a Remote Team of Developers.
Download NowMindbowser played a crucial role in helping us bring everything together into a unified, cohesive product. Their commitment to industry-standard coding practices made an enormous difference, allowing developers to seamlessly transition in and out of the project without any confusion....
CEO, MarketsAI
I'm thrilled to be partnering with Mindbowser on our journey with TravelRite. The collaboration has been exceptional, and I’m truly grateful for the dedication and expertise the team has brought to the development process. Their commitment to our mission is...
Founder & CEO, TravelRite
The Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
Mindbowser has truly been foundational in my journey from concept to design and onto that final launch phase.
CEO, KickSnap
We had very close go live timeline and Mindbowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project.
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
Mindbowser was great; they listened to us a lot and helped us hone in on the actual idea of the app. They had put together fantastic wireframes for us.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork