【问题标题】:How to correctly cascade delete secondary object from MongoDB when account is deleted?删除帐户时如何从 MongoDB 中正确级联删除辅助对象?
【发布时间】:2021-10-17 16:49:24
【问题描述】:

用户可以在我的应用上创建帐户,并可以点赞、分享 X 个帖子。

问题是,每当用户删除他/她的帐户时,与他们相关的所有内容也应该被删除;到目前为止,我已经能够修复大部分问题,但是这个:

await this.model('Post').updateMany(
    {
      'sharedby.user': this._id
    },
    {
      $pull: { 'sharedby.user': this._id }
    }
  );

显然,我使用点表示法,因为user 是在Post 模型的sharedby 对象中找到的对象之一。这里是:

sharedby: [
      {
        user: {
          type: mongoose.Schema.Types.ObjectId,
          ref: 'User'
        },
        post: {
          type: mongoose.Schema.Types.ObjectId,
          ref: 'Post'
        }
      }
    ],

只要有share,就会触发这个函数:

const newshare = await Post.findByIdAndUpdate(
    {
      _id: req.params.id,
      sharedby: { $ne: { user: req.user._id } }
    },
    {
      $push: { sharedby: { user: req.user._id, post: post._id } }
    },
    {
      new: true,
      runValidators: true,
      setDefaultsOnInsert: true
    }
  );

差不多就是这样。我真的不知道为什么它不起作用。有什么建议?谢谢!。

【问题讨论】:

    标签: javascript node.js mongodb express mongoose


    【解决方案1】:

    由于您想从sharedby 中删除所有匹配记录,我想您会想使用$pullAll。此外,当使用$pull$pullAll 时,您应该只使用点符号直到数组边界:

    await this.model('Post').updateMany(
      {
        'sharedby.user': this._id
      },
      {
        $pullAll: { 'sharedby': { user: this._id } }
      }
    );
    

    另见:Remove Items from an Array of Documents

    【讨论】:

      猜你喜欢
      • 2011-01-08
      • 2022-09-26
      • 2013-03-17
      • 1970-01-01
      • 2013-10-03
      • 2019-11-25
      • 2013-10-13
      • 2012-07-23
      • 1970-01-01
      相关资源
      最近更新 更多