Sling Academy
Home/Node.js/How to Cascade Delete in Mongoose (with examples)

How to Cascade Delete in Mongoose (with examples)

Last updated: December 30, 2023

Introduction

When dealing with a database, managing related data is an essential aspect of maintaining consistency within the data model. In MongoDB, a non-relational database, the Mongoose ODM (Object Data Modeling) library provides a mechanism to interact with the database using a model-based approach. One common requirement is ensuring that when a document is removed, all its related documents are also deleted to avoid orphaned records and maintain referential integrity. This is known as cascade delete, and in this tutorial, you will learn how to implement cascade deletion in MongoDB using Mongoose, from basic to advanced examples.

Establishing Relationships in Mongoose

The concept of cascading deletions is particularly relevant when dealing with ‘related data’, which in Mongoose are typically represented through references or ‘ObjectId’ pointers between models. We’ll start by establishing two simple models—a User model and a Post model, where each post is authored by a user.

const mongoose = require('mongoose');
const { Schema } = mongoose;

const UserSchema = new Schema({
  username: String,
  email: String,
// Other fields can be added here
});

const PostSchema = new Schema({
  title: String,
  content: String,
  author: { type: Schema.Types.ObjectId, ref: 'User' }
});

const User = mongoose.model('User', UserSchema);
const Post = mongoose.model('Post', PostSchema);

Basic Cascade Delete Implementation

Here’s the foundational concept of a cascade delete with a simple hook that is triggered when a user is deleted, to also delete all posts authored by that user.

UserSchema.pre('remove', async function(next) {
  await Post.deleteMany({ author: this._id });
  next();
});

// Elsewhere in code, when you remove a user
await User.findByIdAndRemove(userId);

This ensures that when a User document is removed, all Post documents with a matching ‘author’ field are also deleted.

Handling Cascade Delete in Nested Structures

Real-world data structures are often nested and more complex. Imagine if our posts could also have comments. These comments should also be deleted when a post is removed. Our models and cascading delete mechanism will change to accommodate this complexity.

const CommentSchema = new Schema({
  content: String,
  post: { type: Schema.Types.ObjectId, ref: 'Post' },
  codedBy: { type: Schema.Types.ObjectId, ref: 'User' }
});

PostSchema.pre('remove', async function(next) {
  await Comment.deleteMany({ post: this._id });
  next();
});

CommentSchema.pre('remove', async function(next) {
  // In case you need actions taken on comments removal
  next();
});

const Comment = mongoose.model('Comment', CommentSchema);

The above changes ensure that when a Post is deleted, all associated Comment documents are also removed.

Advanced Cascading with Queueing

In distributed systems, it’s sometimes prudent to queue delete operations to avoid long-running requests or to deal with relationships recursively. We can integrate a message queue such as RabbitMQ to handle this deferred workload.

UserSchema.pre('remove', async function(next) {
  // This would instead enqueue the operation
  await someQueue.send({ type: 'DELETE_POSTS', userId: this._id });
  next();
});

// Then, a separate worker process would handle the actual deletion
someQueue.process(async (message) => {
  if (message.type === 'DELETE_POSTS') {
    await Post.deleteMany({ author: message.userId });
    // Handle comments deletion if applicable
  }
});

This structure allows us to manage complex deletion operations asynchronously, and spread out the load across different execution contexts.

Error Handling

Error handling is crucial to avoid data inconsistency during cascade deletion failures. Here’s an essential try-catch implementation:

UserSchema.pre('remove', async function(next) {
  try {
    await Post.deleteMany({ author: this._id });
  } catch (error) {
    next(error);
  }
});

The catch block can be developed to handle specific errors thrown when attempting to delete, and act accordingly, perhaps by rolling back changes or by logging the error for future correction.

Conclusion

This guide has walked you through the steps of cascade deletion in Mongoose, including basic implementation, handling nested structures, implementing queuing strategies for advanced cascade delete scenarios, and error handling. Should you follow these patterns with consideration for the unique circumstances of your use case, you’ll be able to maintain the integrity of your related documents effectively. While practicing cascade deletes, it’s essential to account for all possible relations and errors to ensure a robust data model.

Next Article: Understanding the Mongoose exec() Function: Guide With Examples

Previous Article: Mongoose: Exclude fields from query results (with examples)

Series: Mongoose.js Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates