DEV Community

Shreelaxmi Hegde
Shreelaxmi Hegde

Posted on • Edited on

Cascade Deletion: What Happens to Comments When You Delete Your Post MongoDB

When you delete your account or post, everything linked to it(comments, likes, followers) disappears too.

But have you ever wondered what really happens behind the scenes when this deletion occurs?


What Is Cascade Deletion?

Cascade deletion is a common database pattern used to maintain data integrity and avoid storing unnecessary data.

It ensures that when a record (like a user or post) is deleted, all associated entities (comments, likes, etc.) are also removed automatically.


Typical Workflow :

  1. The user clicks Delete Account or Delete Post.
  2. The app shows a confirmation message: once deleted, data cannot be recovered.
  3. On confirmation, the main record (user/post) is deleted.
  4. Then, all related data connected through references are also deleted.

This is the Cascade deletion at work.


Behind the Scenes (in MongoDB)

In databases like MongoDB, data is often spread across multiple collections that are linked together through references rather than direct relationships. Where deleting interconnected data in one go is not possible.

To handle such cases, developers use a concept known as Cascade Deletion (a logic that ensures all dependent records are removed when the parent record is deleted).
Let’s understand this through an example:

Example setup:
Let’s say we’re building a platform where users can create posts.
We can have 2 collections:

  1. users → stores user info like name, followers, etc.
  2. posts → stores post info like content, comments, etc.

Now, to associate users with their posts, we connect the two collections using reference IDs via Mongoose schemas:

const userSchema = new Schema({
  username: String,
  // ...
  posts: [{
      type: Schema.Types.ObjectId,
      ref: "Post", // referencing the "Post" model
    }],
});
Enter fullscreen mode Exit fullscreen mode

In MongoDB, collections are linked by reference IDs, not by embedding actual data.
So, when a user is deleted, their posts don’t automatically get removed from the page or the database. They still exist, pointing to a user who no longer exists.

To handle this properly, we define a post middleware in Mongoose that runs after a user is deleted.
This middleware deletes all the posts associated with that user.

userSchema.post("findOneAndDelete", async (user) => {
  if (user) {
    await Post.deleteMany({ _id: { $in: user.posts } });
  }
});
Enter fullscreen mode Exit fullscreen mode

This middleware ensures that when a user is deleted, all of their posts are also removed from the database.

This process is known as Cascade Deletion removing all dependent records once the parent record is deleted, keeping the database clean and consistent.


Why It Matters?

  • Keeps the database clean and efficient.
  • Prevents orphaned records (data with no valid reference).
  • Ensures a consistent and reliable user experience.

In short, Cascade deletion is the silent cleaner that ensures the database doesn’t hold on to what no longer exists.

Thanks for reading!

I’m currently building Accommate, a full-stack web app for student accommodation. It is a part of learning while I was building Rating and Comment feature to a specific housing.

I'll be sharing everything I learn as I build it.

If you are building something like this, I'd love to connect and share ideas.

Top comments (11)

Collapse
 
alexandru-ene-dev profile image
Alexandru Ene

After learning a bit of backend development (Node.js, Express.js, MongoDB), I felt kind of dizzy. Too many information about to explode and get lost.

I decided that, instead of going with small projects that won't challenge me so much, to try something bigger, related more to real life, something that I have no idea how to build.

Which I did and noticed you learn a lot more. Because you have to think about file structure, clean code and to make it work, more importantly.

Collapse
 
dshree profile image
Shreelaxmi Hegde

totally agree!
I’ve experienced the same.

One thing I found and have been following is ->
If you are learning a new language or framework, it’s best to start with tutorials and build mini projects to get comfortable with the basics.
Once you’re confident, move on to a fully working project that mimics real-world applications, and keep learning as you build.

When you want to add a new feature, just explore resources based on your needs. Most concepts only truly click when you understand why you need them.

I realized we should think and act like fullstack devs, not just students. Real expertise comes only by getting your hands dirty and building things.

what do you think?

Collapse
 
alexandru-ene-dev profile image
Alexandru Ene

Totally agree. It's mostly my way of learning too. Thinking you are a real dev makes you confident. It helps you keep going and make progress.

Collapse
 
xwero profile image
david duymelinck

I would have comments and likes as a part of the posts. I would only reference the the user id of the comments and likes.

Collapse
 
dshree profile image
Shreelaxmi Hegde

Yes,
Depending on our needs and how collections are related (like one to one, one to few, or one to many), we have to design the database and decide whether to embed documents or reference them.

Collapse
 
xwero profile image
david duymelinck

I just wanted to address the example you gave where it looks like comments and likes are in a separate collection.
I think it takes away a bit of the validity of your core argument, which it shouldn't.

Thread Thread
 
dshree profile image
Shreelaxmi Hegde

Yeah, you’re right.
that example did make things a bit confusing 😅
I’ve updated the blog with a clearer one that fits the context better. Thanks for pointing it out!

Collapse
 
suryakant_91 profile image
Suryakant Kumar

Nice. It helps me.

Collapse
 
dshree profile image
Shreelaxmi Hegde

Glad it helped! 😊

Some comments may only be visible to logged-in visitors. Sign in to view all comments.