Search code examples
javascriptnode.jsmongodbmongoosemongoose-schema

Delete comment parents in mongoose


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?


Solution

  • 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 })))
            }
        }
    })