MongoDB 删除用户时用户创建的所有文档



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

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

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

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

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

如果您在用户中收集了注释的 ID,则:

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

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

remove(( 没有查询钩子,只针对文档。

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

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

如果您使用的是父引用

userSchema.post('findOneAndDelete', async id => {
await Comments.deleteMany({ user: id });
});

如果您使用的是子引用

userSchema.post("findOneAndDelete", async function (user) {
if (user.comments.length) {
const res = await Comment.deleteMany({ _id: { $in: user.comments } });
console.log(res);
}
});

最新更新