关于node.js:MongoDB删除用户时删除该用户创建的所有文档

MongoDB Delete all documents that created by user when deleting user

我正在研究MongoDB(猫鼬)和NodeJS。我有个问题。我是一个RESTful API。我有用户模型(集合)和评论模型(集合)。用户创建评论,我将用户和用户的评论与用户的_id相关联。我想删除用户删除后的所有评论。我如何在MongoDB中做到这一点?我在Google上搜索了2天,但是找不到很好的消息来源,看了一下MongoDB手册文档,但是我什么都没找到。

请帮助我。谢谢,祝你有美好的一天...


MongoDB不支持集合之间的内置关系和事务。

要删除相关注释(我想您在每个Comment中都有userId字段):

1
db.comments.remove({userId: removedUserId})

如果您在"用户"中有注释ID的集合,则:

1
db.comments.remove({id: {$in: collectionOfCommentIds}})

猫鼬不支持中间件。但请注意,

There is no query hook for remove(), only for documents.

因此您可以定义remove挂钩以与user.remove()一起使用。但不适用于User.remove({_id: userId})

1
2
3
userSchema.post(`remove`, (user) => {
    Comments.remove({userId: user._id})
})