简体   繁体   English

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

[英]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.

相关问题 MongoDb 通过传递用户 id 删除文档 - MongoDb delete documents by passing user id 在删除 mongodb 和 nodejs 中的相应用户之前,删除与用户相关的博客文章 - Delete the associated blog posts with user before deleting the respective user in mongodb and nodejs 删除 Mongo shell 中 MongoDB collections 中的所有文档 - Delete all documents in MongoDB collections in Mongo shell mongodb 中的 deleteMany() 不删除文档 - deleteMany() in mongodb not deleting documents 我试图通过让用户在搜索框中输入名称来查询mongoDB,然后查找与该搜索匹配的所有文档 - I am trying to query mongoDB by having the user enter a name in a search box, then finding all documents that match that search 使用 MongoDB 和 Express 删除顶部项目时删除数据库中的所有嵌套项目 - Delete all nested items in database when deleting a top item using MongoDB and Express 从所有设备中删除用户并注销该用户 - Delete User and Logout that user from all Devices Discord.js 触发时删除所有机器人和用户消息 - Discord.js delete all bot and user message when trigger "我不确定如何使用 MongoDB 删除用户" - Im not sure how to delete a user using MongoDB 需要为每个用户nodejs和mongodb获取一个文档 - Need to fetch one documents per user nodejs and mongodb
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM