Atomic Deletion in Mongodb

116 Views Asked by At

I have the following collections in my MongoDB

Task:

{
_id: string;
name: string;
}

Employee:

{
_id:string;
name: string;
tasks: string[];// contains the ids of the assigned tasks.
}

I want to delete a task if it's not assigned to any employee, so I tried the following code(typescript)

1-async deleteTask(taskID:string){
2-const emp =await db.employeesCollection.findOne({tasks:taskID});
3-if(emp) throw WrongOperationException("can't delete task while some employees working on it.");
4-// race condition could occur here when someone assign the task to some employees 
5-await db.tasksCollection.deleteOne({_id:taskID});
6-}

the function is working fine but as mentioned in the comment, a race condition may occur before the deletion actually committed which will cause some employees to be assigned to a task that doesn't exist.

what's the best solution to make sure that the task is not assigned to any employee before deletion?

0

There are 0 best solutions below