简体   繁体   中英

Concurrent control for NodeJS and MongoDB stack

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.

  • Tasks have states: Pending, Working, Completed
  • Initially when tasks are submitted, they are in "Pending" state.
  • When a user wants to work on a task they query one "Pending" task in FIFO fashion.
  • Upon giving a task to a user, that task is updated to have the state "Working"

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM