MongoDB Delete Document

MongoDB Delete Document

MongoDB Delete Document

Posts are stored as documents in a MongoDB collection on a post-based website, such as a blog or forum. Sometimes, you need to delete posts when they are no longer relevant, contain errors, or violate policies. This guide explains step-by-step instructions on how to delete a post (document) from MongoDB using Node.js, Express.js, and Mongoose.

1. Understanding MongoDB Document Deletion

MongoDB provides multiple ways to delete documents:

  1. deleteOne(filter) – Deletes the first matching document.
  2. deleteMany(filter) – Deletes multiple matching documents.
  3. findByIdAndDelete(id) – Deletes a document by its unique _id and returns it.

For our post-based website, we use findByIdAndDelete(id) since each post has a unique _id.

2. How Deletion Works in a Post Website

A. The Process

  1. The user requests to delete a specific post (via a button in the UI or API call).
  2. The server receives the request and verifies if the post exists.
  3. If the post is found, it gets removed from the database.
  4. If the post does not exist, an appropriate error is returned.
  5. The client (e.g., website or mobile app) confirms the deletion to the user.

B. Why Deleting by _id is Recommended

  • _id is a unique identifier in MongoDB.
  • Deleting by _id ensures the correct post is removed.
  • It's faster compared to searching for a post by title or author.

3. Implementing Post Deletion in a Website

A. Connecting to MongoDB

To interact with MongoDB, we use Mongoose, a Node.js library for MongoDB.

  1. Set up the connection (in database.js):
    const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/blogDB', { useNewUrlParser: true, useUnifiedTopology: true });
  2. Define a schema for posts (in Post.js):
    const mongoose = require('mongoose'); const postSchema = new mongoose.Schema({ title: String, content: String, author: String, createdAt: { type: Date, default: Date.now } }); const Post = mongoose.model('Post', postSchema); module.exports = Post;

B. Deleting a Post from the Database

To remove a post, we use the DELETE HTTP method in our API.

  1. Create a delete function (in postRoutes.js):

    const express = require('express'); const router = express.Router(); const Post = require('../models/Post'); // DELETE request to remove a post by ID router.delete('/:id', async (req, res) => { try { const deletedPost = await Post.findByIdAndDelete(req.params.id); if (!deletedPost) { return res.status(404).json({ message: "⚠️ Post not found!" }); } res.json({ message: "✅ Post deleted successfully", post: deletedPost }); } catch (error) { res.status(500).json({ message: "❌ Error deleting post", error }); } }); module.exports = router;
  2. Add the route to the Express server (in server.js):

    const express = require('express'); const app = express(); const postRoutes = require('./routes/postRoutes'); app.use(express.json()); app.use('/api/posts', postRoutes); app.listen(3000, () => console.log("🚀 Server running on port 3000"));

C. Testing Post Deletion

  1. Start the server
    node server.js
  2. Delete a post using cURL or Postman
    curl -X DELETE http://localhost:3000/api/posts/65d1234abcde67890fgh1234
    Response:
    { "message": "✅ Post deleted successfully", "post": { "_id": "65d1234abcde67890fgh1234", "title": "My First Blog", "content": "This is my first post", "author": "John Doe" } }
  3. Verify in MongoDB
    Open MongoDB shell and check if the post is removed:
    mongo use blogDB db.posts.find()
    The post should no longer be in the database.

4. Additional Enhancements

A. Soft Delete (Instead of Hard Delete)

Instead of deleting a post permanently, mark it as deleted using a deletedAt timestamp.

const postSchema = new mongoose.Schema({ title: String, content: String, author: String, deletedAt: { type: Date, default: null } }); async function softDeletePost(postId) { await Post.findByIdAndUpdate(postId, { deletedAt: new Date() }); }

B. Authentication for Deleting Posts

Only allow admins or post authors to delete posts.

router.delete('/:id', authMiddleware, async (req, res) => { if (req.user.role !== "admin") { return res.status(403).json({ message: "🚫 Not authorized to delete this post!" }); } // Proceed with deletion });

5. Summary

  • We used MongoDB to delete posts from a blog website.
  • We built an API using Express and Mongoose to handle deletion.
  • We tested the deletion using Postman and cURL.
  • We added additional features like soft delete and authentication.

6. Next Steps

Want more? Here are extra improvements: ✅ Restore Soft Deleted Posts
Logging Deleted Posts for Moderation
Send Notification When a Post is Deleted

Would you like me to help with these features? 🚀

Souy Soeng

Souy Soeng

Our website teaches and reads PHP, Framework Laravel, and how to download Admin template sample source code free. Thank you for being so supportive!

Github

Post a Comment

CAN FEEDBACK
close