Start a new topic

How do I cascade delete entities from related collections?

I have 2 collections: projects and tasks.



Projects have references to tasks. I want to delete all referenced tasks when I delete a project.
1 Comment

The best way to do this is through business logic. The logic should be something like the following:



Using the collectionAccess module, find the records from the project collection that are going to be deleted by obtaining the query for deletion and executing it.



Using the async module (for speed and parallel processing), iterate through each project record to be deleted, and delete the task records associated with it.



Use a pre-delete Collection Hook on the Project collection and use code similar to the following.



function onPreDelete(request, response, modules){

var projectCollection = modules.collectionAccess.collection("project");

var taskCollection = modules.collectionAccess.collection("task");

var query = request.params.query;

var entityId = request.entityId;

var logger = modules.logger;

var async = modules.async;



if (entityId) {

query = {"_id": modules.collectionAccess.objectID(entityId)};

}

var iterator = function(item, callback) {

taskCollection.remove({"projectID":item._id}, function (err, result) {

if (err) {

callback(err);

} else {

callback();

}

});

};

var finalCallback = function(err) {

if (err) {

return response.error(err);

} else {

return response.continue();

}

};

var projectFindCallback = function(err, docs) {

if (err) {

logger.error('Query failed: '+ err);

response.body.debug = err;

response.complete(500);

} else {

logger.info("Found project.");

async.each(docs, iterator, finalCallback);

}

};

projectCollection.find(query, projectFindCallback);

}

Login or Signup to post a comment