Building a Robust CRUD Application with Node.js and MongoDB

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.

Prerequisites

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.

Setting Up the Project

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

Setting Up the Server

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

Check Out What It Takes to Build A Successful App Here

Create Operation

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.

Read Operations

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.

Update Operation

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.

Delete Operation

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.

coma

Conclusion

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 K

Associate Software Engineer

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.

Keep Reading

Keep Reading

  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?