[英]MongoDB Delete all documents that created by user when deleting user
I'm working on MongoDB (mongoose) and NodeJS.我正在研究 MongoDB(猫鼬)和 NodeJS。 I have a problem.我有个问题。 I'm makine a RESTful API.我正在制作一个 RESTful API。 I have Users model (collection) and Comments model (collection).我有用户模型(集合)和评论模型(集合)。 Users creates comments, and i relate the User and User's Comments with User's _id.用户创建评论,我将用户和用户评论与用户的 _id 相关联。 l want to delete all comments when user deleted.我想在用户删除时删除所有评论。 How can I make this in MongoDB?我怎样才能在 MongoDB 中做到这一点? I search it on Google for 2 days but İ l can't find a good source, looked at MongoDB Manual Documents, but i didn't find anything.我在 Google 上搜索了 2 天,但找不到好的来源,查看了 MongoDB Manual Documents,但我什么也没找到。
Please help me.请帮我。 Thanks, have a good day...谢谢,祝你有美好的一天...
"MongoDB doesn't support built-in relations and transactions among collections. MongoDB不支持集合之间的内置关系和事务。
To remove related Comments (I suppose you have userId
field in each Comment
): 要删除相关的注释(我想您在每个Comment
都有userId
字段):
db.comments.remove({userId: removedUserId})
If you have collection of ids of comments in User, then: 如果您在用户中有注释ID的集合,则:
db.comments.remove({id: {$in: collectionOfCommentIds}})
Mongoose does support middlewares . 猫鼬支持中间件 。 But notice that 但请注意
There is no query hook for remove(), only for documents. 没有针对remove()的查询挂钩,仅针对文档。
So you can define remove
hook for use with user.remove()
. 因此,您可以定义remove
挂钩以与user.remove()
。 But not for User.remove({_id: userId})
但不适用于User.remove({_id: userId})
userSchema.post(`remove`, (user) => {
Comments.remove({userId: user._id})
})
If you are using parent referencing如果您使用父引用
userSchema.post('findOneAndDelete', async id => {
await Comments.deleteMany({ user: id });
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.