I am working on a REST API where I am trying to delete a blog document from my MongoDB database. Everything works fine, and the blog is deleted when I don’t have a reference to a User in the blog document. However, when I add a reference to a User and try to delete the blog, I always get the response Blog not found.
blogController.js–
const { default: mongoose } = require("mongoose");
const blogModel = require("../models/blogModel");
const userModel = require("../models/userModel");
//get all blogs
exports.getAllBlogsController = async (req, res) => {
try {
const allblogs = await blogModel.find({});
if (!allblogs) {
return res.status(500).json({ message: "No blog is present" });
}
return res.status(200).json({ BlogCount: allblogs.length, allblogs });
} catch (error) {
return res.status(500).json({ message: "Server error", error });
}
};
// Create blog
exports.createBlogController = async (req, res) => {
try {
const { title, description, image,user } = req.body;
if (!title || !description || !image || !user) {
return res.status(400).json({ message: "All fields are required" });
}
const existingUser= await userModel.findById(user)
if(!existingUser){
return res.status(404).json({"message":"Unable to find user"})
}
// we will use session of mongoose and then updatethe blog
const newBlog = new blogModel({ title, description, image,user });
const session= await mongoose.startSession()
session.startTransaction()
await newBlog.save({session})
existingUser.blogs.push(newBlog)
await existingUser.save({session})
await session.commitTransaction();
session.endSession();
return res.status(200).json({ message: "blog created", newBlog });
} catch (error) {
res.status(500).json({ message: "Server error", error });
}
};
// update blog
exports.updatBlogController = async (req, res) => {
try {
const {id} = req.params;
const { title, description, image } = req.body;
const blog = await blogModel.findByIdAndUpdate(
id,
{ ...req.body },
{ new: true }
);
return res.status(200).send({
success: true,
message: "Blog updated",
blog,
});
} catch (error) {
return res.status(500).json({ message: "Server error", error });
}
};
// find specfic blog through id
exports.getBlogByIdController = async (req, res) => {
try {
const {id}= req.params
const blog= await blogModel.findById(id);
if(!blog){
return res.status(500).json({"message":"No such kind of blog is present"})
}
return res.status(200).json({blog,"message":"fetched single blog"})
} catch (error) {
return res.status(500).json({ message: "Server error", error });
}
};
// delete blog
exports.deleteBlogController = async (req, res) => {
try {
const { id } = req.params;
// Validate if the provided ID is a valid ObjectId
if (!mongoose.Types.ObjectId.isValid(id)) {
return res.status(400).json({ message: "Invalid blog ID format" });
}
// Find the blog by ID and populate the user field
const blog = await blogModel.findById(id).populate("user");
// If no blog is found, return 404
if (!blog) {
return res.status(404).json({ message: "Blog not found" });
}
// Pull the blog's ObjectId from the user's blogs array
if (blog.user && blog.user.blogs) {
blog.user.blogs.pull(blog._id);
await blog.user.save();
} else {
return res.status(400).json({ message: "User's blogs array not found" });
}
// Delete the blog from the blog collection
await blogModel.findByIdAndDelete(id);
// Successfully deleted the blog and updated the user
return res.status(200).json({ message: "Blog deleted successfully" });
} catch (error) {
console.error(error); // Log for better debugging
return res.status(500).json({ message: "Server error", error });
}
};
blogModel.js —
const { default: mongoose } = require("mongoose");
const blogModel = require("../models/blogModel");
const userModel = require("../models/userModel");
//get all blogs
exports.getAllBlogsController = async (req, res) => {
try {
const allblogs = await blogModel.find({});
if (!allblogs) {
return res.status(500).json({ message: "No blog is present" });
}
return res.status(200).json({ BlogCount: allblogs.length, allblogs });
} catch (error) {
return res.status(500).json({ message: "Server error", error });
}
};
// Create blog
exports.createBlogController = async (req, res) => {
try {
const { title, description, image,user } = req.body;
if (!title || !description || !image || !user) {
return res.status(400).json({ message: "All fields are required" });
}
const existingUser= await userModel.findById(user)
if(!existingUser){
return res.status(404).json({"message":"Unable to find user"})
}
// we will use session of mongoose and then updatethe blog
const newBlog = new blogModel({ title, description, image,user });
const session= await mongoose.startSession()
session.startTransaction()
await newBlog.save({session})
existingUser.blogs.push(newBlog)
await existingUser.save({session})
await session.commitTransaction();
session.endSession();
return res.status(200).json({ message: "blog created", newBlog });
} catch (error) {
res.status(500).json({ message: "Server error", error });
}
};
// update blog
exports.updatBlogController = async (req, res) => {
try {
const {id} = req.params;
const { title, description, image } = req.body;
const blog = await blogModel.findByIdAndUpdate(
id,
{ ...req.body },
{ new: true }
);
return res.status(200).send({
success: true,
message: "Blog updated",
blog,
});
} catch (error) {
return res.status(500).json({ message: "Server error", error });
}
};
// find specfic blog through id
exports.getBlogByIdController = async (req, res) => {
try {
const {id}= req.params
const blog= await blogModel.findById(id);
if(!blog){
return res.status(500).json({"message":"No such kind of blog is present"})
}
return res.status(200).json({blog,"message":"fetched single blog"})
} catch (error) {
return res.status(500).json({ message: "Server error", error });
}
};
// delete blog
exports.deleteBlogController = async (req, res) => {
try {
const { id } = req.params;
// Validate if the provided ID is a valid ObjectId
if (!mongoose.Types.ObjectId.isValid(id)) {
return res.status(400).json({ message: "Invalid blog ID format" });
}
// Find the blog by ID and populate the user field
const blog = await blogModel.findById(id).populate("user");
// If no blog is found, return 404
if (!blog) {
return res.status(404).json({ message: "Blog not found" });
}
// Pull the blog's ObjectId from the user's blogs array
if (blog.user && blog.user.blogs) {
blog.user.blogs.pull(blog._id);
await blog.user.save();
} else {
return res.status(400).json({ message: "User's blogs array not found" });
}
// Delete the blog from the blog collection
await blogModel.findByIdAndDelete(id);
// Successfully deleted the blog and updated the user
return res.status(200).json({ message: "Blog deleted successfully" });
} catch (error) {
console.error(error); // Log for better debugging
return res.status(500).json({ message: "Server error", error });
}
};
usermodel.js
const mongoose= require('mongoose')
const userSchema= new mongoose.Schema({
username:{
type:String,
required:[true,'username is required']
},
email:{
type:String,
required:[true,'email is required'],
unique:true
},
password:{
type:String,
required:[true,'password is required'],
unique:true
},
blogs:[
{
type:mongoose.Types.ObjectId,
ref: 'Blog',
}
]
},{timestamps:true})
const userModel= mongoose.model('User',userSchema)
module.exports= userModel;
blogRoutes.js
//Delete blog
router.delete('/delete-blog/:id',deleteBlogController);
server.js —
//routes
app.use('/api/v1/user',userRoutes);
app.use('/api/v1/blog',blogRoutes);

