【问题标题】:MongoDB Delete all documents that created by user when deleting userMongoDB删除用户时删除用户创建的所有文档
【发布时间】:2018-11-21 16:01:13
【问题描述】:

我正在研究 MongoDB(猫鼬)和 NodeJS。我有个问题。我正在制作一个 RESTful API。我有用户模型(集合)和评论模型(集合)。用户创建 cmets,我将用户和用户的评论与用户的 _id 关联起来。我想在用户删除时删除所有 cmets。我怎样才能在 MongoDB 中做到这一点?我在 Google 上搜索了 2 天,但我找不到好的来源,查看了 MongoDB Manual Documents,但我没有找到任何东西。

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

【问题讨论】:

  • 请贴一个你拥有的数据结构的例子

标签: node.js mongodb mongoose


【解决方案1】:

如果您使用父引用

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

【讨论】:

    【解决方案2】:

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

    要删除相关的评论(我想你在每个 Comment 中都有 userId 字段):

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

    如果您在 User 中有 cmets 的 id 集合,则:

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

    Mongoose 确实支持middlewares。但请注意

    remove() 没有查询钩子,仅适用于文档。

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

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

    【讨论】:

    • $in 运算符选择字段值等于指定数组中的任何值的文档。 collectionOfCommentIds 需要一个数组...
    • 好的。非常感谢@iofjuupasli。你帮了我太多了:)
    • @Rags-2-Riches 是的,它可以在需要时提供帮助。感谢您的描述 +1
    猜你喜欢
    • 1970-01-01
    • 2022-11-26
    • 2021-07-15
    • 2020-05-12
    • 2021-07-18
    • 2018-08-28
    • 2021-11-06
    • 1970-01-01
    • 2021-10-19
    相关资源
    最近更新 更多