Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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!.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!