I have these "tasks" that are submitted by users which hits my NodeJS server and stored as documents in MongoDB database. These tasks are then also fetched by users and worked on one at a time.
My problem is when two users simultaneously ask for a task to work on, they might get the same task due to race condition. While the first query tries to update the task's state to "Working" second query can fetch that one as well. Could someone suggest me how I might be able to solve this using NodeJS and MongoDB where everything is asynchronous? Any frameworks or libraries are also welcomed too.
MongoDB has a findAndModify
method exactly for that purpose.
Using the MongoDB driver, you would run the following code,
collection.findAndModify({
// Query
}, [
// Sort
], {
$set: {
state: 'working'
}
}, {
new: true
}).then((task) => {
// This is your "working" task
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.