Cascade style delete in Mongoose
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()
.
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.