简体   繁体   English

NodeJS和MongoDB堆栈的并发控制

[英]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. 我有用户提交的这些“任务”,这些命中了我的NodeJS服务器,并作为文档存储在MongoDB数据库中。 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. 当用户想要处理任务时,他们以FIFO方式查询一个“待处理”任务。
  • 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? 有人可以建议我如何使用NodeJS和MongoDB解决所有异步的问题吗? Any frameworks or libraries are also welcomed too. 也欢迎任何框架或库。

MongoDB has a findAndModify method exactly for that purpose. MongoDB正是有一个为此目的的findAndModify方法。

Using the MongoDB driver, you would run the following code, 使用MongoDB驱动程序,您将运行以下代码,

collection.findAndModify({
  // Query
}, [
  // Sort
], {
  $set: {
    state: 'working'
  }
}, {
  new: true
}).then((task) => {
  // This is your "working" task
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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