MongoDB Update Document

MongoDB Update Document

MongoDB Update Document

Updating a document in MongoDB is essential for managing dynamic content on a post-based website. This guide will explain how to update a blog post using Node.js, Express.js, and Mongoose.


1. Understanding MongoDB Update Operations

MongoDB provides multiple methods to update documents:

  1. updateOne(filter, updateData) – Updates the first matching document.
  2. updateMany(filter, updateData) – Updates all matching documents.
  3. findByIdAndUpdate(id, updateData, options) – Updates a document by its _id and optionally returns the updated document.

For a post-based website, we typically use findByIdAndUpdate(id, updateData, { new: true }), which:

  • Finds a document by _id.
  • Updates the specified fields.
  • Returns the updated document.

2. How Updating Works in a Post Website

A. The Update Process

  1. The user requests to update a specific post (via a form or API call).
  2. The server receives the request and verifies if the post exists.
  3. If the post is found, the specified fields are updated.
  4. If the post does not exist, an error message is returned.
  5. The client (e.g., website or mobile app) confirms the update to the user.

B. Example Use Cases

  • A user edits their blog post content.
  • An admin updates a post’s status (e.g., "published" → "archived").
  • A system automatically adds a timestamp when a post is modified.

3. Implementing Post Updates in a Website

A. Connecting to MongoDB

Ensure that MongoDB is running and properly connected.
(See Step 3 of the Delete Guide for setting up the database connection.)

B. Define the Blog Post Model

In models/Post.js, define a schema for the posts:

const mongoose = require('mongoose'); const postSchema = new mongoose.Schema({ title: { type: String, required: true }, content: { type: String, required: true }, author: { type: String, required: true }, updatedAt: { type: Date, default: Date.now } // Track last update time }); const Post = mongoose.model('Post', postSchema); module.exports = Post;

C. Creating an Update Route

In routes/postRoutes.js, create a PUT route to update a post:

const express = require('express'); const router = express.Router(); const Post = require('../models/Post'); // UPDATE a post by ID router.put('/:id', async (req, res) => { try { const updatedPost = await Post.findByIdAndUpdate( req.params.id, { ...req.body, updatedAt: Date.now() }, // Update fields and timestamp { new: true, runValidators: true } // Return updated document and validate data ); if (!updatedPost) { return res.status(404).json({ message: "⚠️ Post not found!" }); } res.json({ message: "✅ Post updated successfully", post: updatedPost }); } catch (error) { res.status(500).json({ message: "❌ Error updating post", error }); } }); module.exports = router;

D. Add the Route to the Express Server

In server.js, register the update route:

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

4. Testing Post Updates

A. Start the Server

Run the Node.js server:

node server.js

B. Create a Sample Post

Before updating a post, create one using Postman or cURL:

curl -X POST http://localhost:3000/api/posts -H "Content-Type: application/json" -d '{ "title": "My First Blog", "content": "This is my first post", "author": "John Doe" }'

This will return a response like:

{ "title": "My First Blog", "content": "This is my first post", "author": "John Doe", "_id": "65d1234abcde67890fgh1234", "updatedAt": "2025-02-02T12:00:00.000Z" }

C. Update the Post

Now update the post’s content:

curl -X PUT http://localhost:3000/api/posts/65d1234abcde67890fgh1234 -H "Content-Type: application/json" -d '{ "title": "Updated Blog Title", "content": "This is my updated post content" }'

Response:

{ "message": "✅ Post updated successfully", "post": { "_id": "65d1234abcde67890fgh1234", "title": "Updated Blog Title", "content": "This is my updated post content", "author": "John Doe", "updatedAt": "2025-02-02T12:05:00.000Z" } }

D. Verify in MongoDB

Check the updated post in MongoDB:

mongo use blogDB db.posts.find().pretty()

You should see the updated content.

5. Enhancements

A. Allow Partial Updates with patch

Use PATCH instead of PUT if only some fields need updating:

router.patch('/:id', async (req, res) => { try { const updatedPost = await Post.findByIdAndUpdate( req.params.id, { ...req.body, updatedAt: Date.now() }, { new: true, runValidators: true } ); if (!updatedPost) { return res.status(404).json({ message: "⚠️ Post not found!" }); } res.json({ message: "✅ Post updated successfully", post: updatedPost }); } catch (error) { res.status(500).json({ message: "❌ Error updating post", error }); } });

Now users can update only one field without sending the entire post object.

B. Add Authentication (Only Authors Can Update Their Posts)

Modify the PUT route to check if the user is the author:

router.put('/:id', authMiddleware, async (req, res) => { try { const post = await Post.findById(req.params.id); if (!post) return res.status(404).json({ message: "⚠️ Post not found!" }); if (post.author !== req.user.username) { return res.status(403).json({ message: "🚫 Not authorized to update this post!" }); } const updatedPost = await Post.findByIdAndUpdate(req.params.id, req.body, { new: true }); res.json({ message: "✅ Post updated successfully", post: updatedPost }); } catch (error) { res.status(500).json({ message: "❌ Error updating post", error }); } });

6. Summary

We used MongoDB to update blog posts.
We built an API with Express.js and Mongoose to handle updates.
We tested updates using Postman and cURL.
We added security features (authentication & partial updates).

7. Next Steps

🔹 Implement Soft Updates (Track Edit History)
🔹 Send Notifications When a Post is Updated
🔹 Optimize Performance for Bulk Updates

Would you like me to help with these enhancements? 🚀

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