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 :
- The user clicks Delete Account or Delete Post.
- The app shows a confirmation message: once deleted, data cannot be recovered.
- On confirmation, the main record (user/post) is deleted.
- 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:
- users → stores user info like name, followers, etc.
- 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
}],
});
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 } });
}
});
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)
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.
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?
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.
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.
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.
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.
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!
Nice. It helps me.
Glad it helped! 😊
Some comments may only be visible to logged-in visitors. Sign in to view all comments.