Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cascade style delete in Mongoose

People also ask

What is Cascade delete in MongoDB?

Using those concepts, it allows a “cascading'' delete, which means a primary key parent delete will delete the related siblings. MongoDB allows you to form relationships in different ways—for example, by embedding documents or arrays inside a parent document.

How works on delete cascade?

Use the ON DELETE CASCADE option to specify whether you want rows deleted in a child table when corresponding rows are deleted in the parent table. If you do not specify cascading deletes, the default behavior of the database server prevents you from deleting data in a table if other tables reference it.

What is on delete cascade example?

ON DELETE CASCADE constraint is used in MySQL to delete the rows from the child table automatically, when the rows from the parent table are deleted. For example when a student registers in an online learning platform, then all the details of the student are recorded with their unique number/id.


This is one of the primary use cases of Mongoose's 'remove' middleware.

clientSchema.pre('remove', function(next) {
    // 'this' is the client being removed. Provide callbacks here if you want
    // to be notified of the calls' result.
    Sweepstakes.remove({client_id: this._id}).exec();
    Submission.remove({client_id: this._id}).exec();
    next();
});

This way, when you call client.remove() this middleware is automatically invoked to clean up dependencies.


In case your references are stored other way around, say, client has an array of submission_ids, then in a similar way as accepted answer you can define the following on submissionSchema:

submissionSchema.pre('remove', function(next) {
    Client.update(
        { submission_ids : this._id}, 
        { $pull: { submission_ids: this._id } },
        { multi: true })  //if reference exists in multiple documents 
    .exec();
    next();
});

which will remove the submission's id from the clients' reference arrays on submission.remove().


Here's an other way I found

submissionSchema.pre('remove', function(next) {
    this.model('Client').remove({ submission_ids: this._id }, next);
    next();
});