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 in Node-js by Ashutosh
• 19,190 points
56 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 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 in Node-js by Kavya
42 views
0 votes
1 answer

How to use executables from a package installed locally in node_modules?

Hello @kartik, Use the npm bin command to get the ...READ MORE

answered Jul 13, 2020 in Node-js by Niroj
• 82,840 points
1,683 views
0 votes
1 answer

How to use MongoDB with promises in Node.js?

Hello @kartik, Try this: var MongoClient = require('mongodb').MongoClient var url ...READ MORE

answered Oct 12, 2020 in Node-js by Niroj
• 82,840 points
1,546 views
0 votes
1 answer

How to “Ping” from a Node.js app?

Hello @kartik, You could use exec to call the system ...READ MORE

answered Oct 16, 2020 in Node-js by Niroj
• 82,840 points
4,870 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 in Node-js by Kavya
43 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 in Node-js by Kavya
48 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 in Node-js by anonymous
77 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 in Node-js by Kavya
59 views
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