I have been on this for days. I have tried so many things. I know I am not doing it rightly. I have a blog application I am building using node.js, mongodb and react.js. So, I have User Model, Post Model and Comment Model so far. I linked them up. What I did for post and comment models is this: When a user who made a comment deletes the comment, I want the referenced id of that comment in Post collection to be deleted as well from the database. It makes no sense if the comment referenced id remains in the database even though it has no content in it. It can be messy when you have many deleted comments. Comment Model is referenced in Post model. So, when a comment is deleted in Comment collection, the id referenced in the Post collection should be deleted as well. Look at my codes so far:
Comment model
const mongoose = require("mongoose"); //import mongoose to be used
const Schema = mongoose.Schema;
const CommentSchema = new mongoose.Schema(
{
commentdescription:{
type: String,
required: true,
},
author:{
type: Schema.Types.ObjectId,
ref: 'User',
},
postId:{
type: Schema.Types.ObjectId,
ref: "Post",
}
}, {timestamps: true}
);
CommentSchema.pre('update',function(next) {
this.model('Post').update(
{ },
{ "$pull": { "comments": this._id } },
{ "multi": true },
next
);
})
//exporting this schema
module.exports = mongoose.model("Comment", CommentSchema); //the module name is "Post"
I saw a post on this site about doing this with Mongodb middleware. I applied the middleware code inside my Comment Model as you can see above. It is not working. After deleting a comment, the referenced id in the Post collection is still there in the array. I am sure I am not doing it rightly.
Post Model
//creating the user models for the database
const mongoose = require("mongoose"); //import mongoose
const Schema = mongoose.Schema;
const PostSchema = new mongoose.Schema(
{
title:{
type: String,
required: true,
unique: true,
},
description:{
type: String,
required: true,
},
postPhoto:{
type: String,
required:false,
},
username:{
type: Schema.Types.ObjectId,
ref: 'User'
},
categories:{
type: Array,
},
comments: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Comment',
unique: true,
}]
}, {timestamps: true},
);
//exporting this schema
module.exports = mongoose.model("Post", PostSchema); //the module name is "Post"
Comment deleting code
router.delete("/posts/:id/comment/:id", async (req, res) =>{
try{
const comment = await Comment.findById(req.params.id);
if(comment.author == req.body.author){
try{
await comment.delete()
res.status(200).json("Comment has been deleted")
}catch(err){
console.log(err)
}
}
else{
res.status(401).json("you can only delete your posts")
}
}catch(err){
console.log(err)
}
})
fetching post codes
//Get Post
router.get("/:id", async(req, res)=>{
try{
const post = await Post.findById(req.params.id).populate('username').populate({
path: "comments",
populate: {
path: "author",
}
})
This is a screenshot of the referenced id I am talking about. This particular comment has been deleted but the id is still found in that particular post array where the comment was made.
CodePudding user response:
Your code would be somewhat like this:
deleteCommentById: async function (req, res) {
try {
if (req.params.type === "Comment") {
await postModel.updateMany({ postId: ObjectId(req.params.postId), type: 'Post' }, { $pull: { 'children': ObjectId(req.params.id) } });
await commentModel.updateMany({ postId: ObjectId(req.params.postId) }, { $pull: { 'comments': ObjectId(req.params.id) } });
}
await postModel.findByIdAndDelete(ObjectId(req.params.id));
return res.status(http_status.OK).json({ message: `${req.params.type} deleted successfully` });
} catch (error) {
return res.send("error");
}
}
SO, your code too will be somewhat like the code above which I have written as reference for you.
CodePudding user response:
So instead of this :
CommentSchema.pre('update',function(next) {
Try to use .pre('remove') or .pre('delete') instead of update