Home > front end >  Delete comment parents in mongoose
Delete comment parents in mongoose

Time:12-02

I am using typegoose and type-graphql. I have a CommentModel which has a parentId field that stores ObjectId of its parent comment.

What do I want?

I want to automate deletion of parents by using pre middleware. means when I delete a comment, I want it to delete all the comments that their parentId equals to targeted comment id.

An example:

So, when I delete comment 2, I expect the comment 1 will be deleted too.

comment: [
    {
        _id: 1,
        parentId: 2
    }, 
    {
        _id: 2,
        parentId: null
    }
]

but I can't.

What did I do?

this is my middleware:

@pre(/remove|delete/i, async function () {
    await CommentModel.deleteMany({ parentId: this._id })
})
export class Comment {
   ...
}

export const CommentModel = getModelForClass(Comment)

And this is how I delete

await CommentModel.findByIdAndDelete(ID_OF_COMMENT)

this operation will NEVER finish. and always show me the loading spinner. What do you suggest? Am I doing it wrong? or there is a better approach?

CodePudding user response:

every middelware have a next funxtion to continue change it like this:

@pre(/remove|delete/i, async function (next) {
await CommentModel.deleteMany({ parentId: this._id })
next();
})

CodePudding user response:

This is how I fixed it:

@post(/remove|delete/i, async function (comment: DocumentType<Comment> | null) {
    if (comment?._id) {
        const children = await CommentModel.find({ parentId: comment._id }).lean().exec()
        await CommentModel.deleteMany({ parentId: comment._id })
        if (children) {
            await Promise.all(children.map(child => child?._id && CommentModel.deleteMany({ parentId: child._id })))
        }
    }
})
  • Related