How can you use MongoDB CRUD operations to build a simple blog app

0 votes
With the help of proper code snippet can you explain How can you use MongoDB CRUD operations to build a simple blog app?
Feb 22, 2025 in Node-js by Ashutosh
• 33,350 points
496 views

1 answer to this question.

0 votes

Below is a simple implementation using MongoDB with Node.js and Express.js.

1. Setting Up the Blog App

Install Dependencies

npm init -y

npm install express mongoose body-parser cors

Express.js: Web framework for Node.js.

Mongoose: ODM (Object Data Modeling) for MongoDB.

Body-parser: Middleware for handling request data.

CORS: Allows API requests from different origins.

2. Connecting to MongoDB

Create a file server.js and set up MongoDB connection:

const express = require("express");

const mongoose = require("mongoose");

const bodyParser = require("body-parser");

const cors = require("cors");

const app = express();

app.use(bodyParser.json());

app.use(cors());

// Connect to MongoDB

mongoose

  .connect("mongodb://127.0.0.1:27017/blogDB", { useNewUrlParser: true, useUnifiedTopology: true })

  .then(() => console.log("MongoDB connected"))

  .catch((err) => console.log(err));

// Define the Blog Schema

const blogSchema = new mongoose.Schema({

  title: String,

  content: String,

  author: String,

  createdAt: { type: Date, default: Date.now },

});

const Blog = mongoose.model("Blog", blogSchema);

3. Implementing CRUD Operations

(1) Create a Blog Post (C - Create)

app.post("/blogs", async (req, res) => {

  try {

    const { title, content, author } = req.body;

    const newPost = new Blog({ title, content, author });

    await newPost.save();

    res.status(201).json(newPost);

  } catch (err) {

    res.status(500).json({ message: err.message });

  }

});

(2) Read All Blog Posts (R - Read)

app.get("/blogs", async (req, res) => {

  try {

    const posts = await Blog.find();

    res.status(200).json(posts);

  } catch (err) {

    res.status(500).json({ message: err.message });

  }

});

(3) Read a Single Blog Post by ID

app.get("/blogs/:id", async (req, res) => {

  try {

    const post = await Blog.findById(req.params.id);

    if (!post) return res.status(404).json({ message: "Post not found" });

    res.status(200).json(post);

  } catch (err) {

    res.status(500).json({ message: err.message });

  }

});

(4) Update a Blog Post (U - Update)

app.put("/blogs/:id", async (req, res) => {

  try {

    const updatedPost = await Blog.findByIdAndUpdate(req.params.id, req.body, { new: true });

    if (!updatedPost) return res.status(404).json({ message: "Post not found" });

    res.status(200).json(updatedPost);

  } catch (err) {

    res.status(500).json({ message: err.message });

  }

});

(5) Delete a Blog Post (D - Delete)

app.delete("/blogs/:id", async (req, res) => {

  try {

    const deletedPost = await Blog.findByIdAndDelete(req.params.id);

    if (!deletedPost) return res.status(404).json({ message: "Post not found" });

    res.status(200).json({ message: "Post deleted successfully" });

  } catch (err) {

    res.status(500).json({ message: err.message });

  }

});

4. Starting the Server

Add the following at the end of server.js:

const PORT = 5000;

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

Start the server:

node server.js

answered Feb 23, 2025 by Kavya

Related Questions In Node-js

0 votes
1 answer

How would you model a one-to-many relationship in MongoDB?

In MongoDB, a one-to-many relationship can be ...READ MORE

answered Feb 22, 2025 in Node-js by Kavya
540 views
0 votes
1 answer

How to build a real-time chat app with react node Socket.IO and HarperDB?

Set Up HarperDB: Create a HarperDB instance (cloud ...READ MORE

answered Mar 10, 2025 in Node-js by Tanvi
553 views
0 votes
1 answer

How to build a product list app with redux-saga handling data fetching?

Example of Retry Logic with Redux-Saga Import Required ...READ MORE

answered Mar 19, 2025 in Node-js by Tanvi
490 views
0 votes
1 answer

What is the difference between RDBMS relationships and MongoDB’s data model?

Feature RDBMS (SQL Databases) MongoDB (NoSQL Document Database) Data Structure Tables ...READ MORE

answered Feb 23, 2025 in Node-js by Kavya
477 views
0 votes
1 answer
0 votes
1 answer

Write a query for a compound index to optimize a search operation in MongoDB.

A compound index improves search performance by ...READ MORE

answered Feb 23, 2025 in Node-js by Kavya
535 views
0 votes
1 answer

What are MongoDB data types, and how do you define them in a schema?

MongoDB supports various data types, including: String (String) ...READ MORE

answered Feb 23, 2025 in Node-js by anonymous
510 views
0 votes
1 answer

How do you model a many-to-many relationship in MongoDB with an example?

In MongoDB, a many-to-many relationship can be ...READ MORE

answered Feb 23, 2025 in Node-js by Kavya
554 views
0 votes
1 answer
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP