Automattic / Automattic/mongoose

Add Optional Cascading Delete Support to Mongoose Schemas

Open
#15,417 5 comments 0 reactions 0 assignees View on GitHub
enhancement new feature
Dominant language
JavaScript
Stars
27.5k
Forks
4k
Avg merge
2d 7h
Merged PRs (30d)
35

Description

### Prerequisites

- [x] I have written a descriptive issue title
- [x] I have searched existing issues to ensure the feature has not already been requested

### Feature Proposal

# Proposal: Add Automatic Cascading Delete Support to Mongoose Schemas

Hi Mongoose team,

I'd like to contribute a feature that adds **automatic cascading delete support** to Mongoose schemas. This would allow developers to declaratively define relationships where dependent documents should be removed automatically when a parent document is deleted — without needing to manually trigger cascade behavior every time.

---

## Proposed API (Early Draft)

The idea is to allow cascade rules to be declared within schema options, like so:

```js
const userSchema = new mongoose.Schema({
name: String
}, {
cascade: [
{
model: 'Post',
foreignField: 'userId'
}
]
});
```

### Motivation

---

### 2. **Motivation for Automatic Cascading Deletes**

# Motivation for Automatic Cascading Deletes in Mongoose

In Mongoose, cascading deletes are often handled manually by developers using middleware like `pre('remove')` or `pre('deleteOne')`. While this approach works, it can quickly become repetitive, error-prone, and difficult to maintain in larger applications, especially when multiple related models need to be deleted simultaneously.

---

## Why Cascading Deletes Matter

In many database designs, entities are related in a hierarchical or parent-child structure. When a parent document (e.g., `User`) is deleted, it is often necessary to remove its child documents (e.g., `Posts`) to avoid orphaned records and maintain referential integrity.

Adding automatic cascading delete support at the schema level would:
- Reduce boilerplate code
- Enforce consistency across your application
- Simplify complex relationships by removing the need to manually add deletion logic to each model
- Improve developer productivity by allowing focus on business logic, not manual cleanup

---

## Benefits of the Feature
- **Cleaner codebase**: No need to manually write cascade logic for each operation
- **Consistency**: Standardizes the cascade delete approach across projects
- **Error reduction**: Avoids inconsistencies in deletion behavior due to missed middleware or manual logic
- **Ease of use**: Developers can easily define cascading rules directly within their schema

This feature would make cascading deletes **more intuitive** and **seamless** for Mongoose users.

### Example

# Examples of Automatic Cascading Delete in Mongoose

Here are some examples of how automatic cascading delete behavior would work with the proposed feature.

---

## Example 1: Basic One-to-Many Relationship (User → Posts)

Assume you have a `User` model and a `Post` model where `Post` documents have a `userId` field referencing the `User` who created the post.

### Schema Setup:
```js
const userSchema = new mongoose.Schema({
name: String
}, {
cascade: [
{
model: 'Post',
foreignField: 'userId'
}
]
});
await user.deleteOne({name:"user_name"}); // Automatically deletes all related posts
```
# Example 2: More Complex Relationships (Course → Lessons)

Imagine a `Course` model with an array of `Lesson` documents embedded or referenced within it.

### Schema Setup:
```js
const courseSchema = new mongoose.Schema({
title: String,
lessons: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Lesson' }]
}, {
cascade: [
{
model: 'Lesson',
foreignField: 'courseId'
}
]
});

Contributor guide

Open the contributing guide

Research direction

The issue names no repository files or tests. Start by reviewing schema options and the existing deleteOne, remove, and delete middleware paths mentioned in the proposal, then establish the API, relationship semantics, and operation coverage. Done should be an agreed, documented, and tested cascade feature.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, mongodb
Domain
backend, database
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.