How to correctly cascade delete secondary object from MongoDB when account is deleted?

Viewed 300

Users can create accounts on my app and are allowed to like, share X post.

The thing is that whenever a user deletes his/her account, everything related to them should also be deleted; so far I've been able to fix most of it but this:

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

Obviously, I'm using dot notation since user is one of the objects found in the sharedby object from the Post model. Here it is:

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

Whenever there's a share, this function gets triggered:

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

That's pretty much about it. I really have no idea why it's not working. Any suggestions? Thanks!.

1 Answers

Since you want to delete all the matching records from sharedby, I imagine you'll want to use $pullAll. Also, when using $pull or $pullAll, you should only use dot notation up to the Array boundary:

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

See also: Remove Items from an Array of Documents

Related