Let’s say I have two types of MongoDB documents: ‘Projects’ and ‘Tasks’. A Project can have many tasks. In my case it is more suitable to link the documents rather than embed.
When a user wants to save a task I first verify that the project the task is being assigned to exists, like so:
// Create new task
var task = new Task(data);
// Make sure project exists
Project.findById(task.project, function(err, project) {
if(project) {
// If project exists, save task
task.save(function(err){
...
});
} else {
// Project not found
}
});
My concern is that if another user happens to delete the project after the Project.findById() query is run, but before the task is saved, the task will be created anyway without a referenced project.
Is this a valid concern? Is there any practice that would prevent this from happening, or is this just something that has to be faced with MongoDB?
Technically yes, this is something you need to face when using MongoDB. But it’s not really a big deal as it’s rarely someone to delete a project and another person is unaware of it and creating task for that project. I would not use the
ifstatement to check the project status, rather just leave task created as a bad record. You can either manually remove those bad records or schedule a cron task to clean them.