删除猫鼬中的评论父母



我使用的是typegoose和typegraphql。我有一个CommentModel,它有一个存储其父注释的ObjectId的parentId字段。

我想要什么

我想通过使用pre中间件来自动删除父母。意味着当我删除评论时,我希望它删除其parentId等于目标评论id的所有评论。

示例:

所以,当我删除评论2时,我希望评论1也会被删除。

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

但我做不到。

我做了什么

这是我的中间件:

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

这就是我删除的方法

await CommentModel.findByIdAndDelete(ID_OF_COMMENT)

这个操作永远不会完成。总是给我看装载旋转器。你有什么建议?我做错了吗?还是有更好的方法?

每个中间件都有下一个功能来继续这样更改:

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

这就是我修复它的方法:

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

最新更新