【问题标题】:Delete comment parents in mongoose删除猫鼬中的评论父母
【发布时间】:2022-01-08 22:40:03
【问题描述】:

我正在使用 typegoose 和 type-graphql。 我有一个CommentModel,它有一个parentId 字段,用于存储其父评论的ObjectId。

我想要什么?

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

一个例子:

所以,当我删除评论 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)

此操作将永远不会完成。总是给我看加载微调器。 你有什么建议?我做错了吗?还是有更好的方法?

【问题讨论】:

    标签: javascript node.js mongodb mongoose mongoose-schema


    【解决方案1】:

    每个 middelware 都有一个下一个功能来继续更改它,如下所示:

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

    【讨论】:

    • 不,我发现问题出在哪里了。
    • deleteMany 返回一个deletedCount 的对象,并且还调用带有对象的钩子:{deletedCount: 1},它没有_id 属性,它使用未定义的_id 调用deleteMany。这形成了一个循环。我通过类型检查修复了它。 if(this._id){}
    【解决方案2】:

    这就是我修复它的方法:

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

    【讨论】:

      猜你喜欢
      • 2020-07-06
      • 1970-01-01
      • 2020-10-11
      • 2011-12-18
      • 1970-01-01
      • 2018-06-11
      • 2021-05-01
      • 1970-01-01
      • 2021-07-08
      相关资源
      最近更新 更多