猫鼬多个相关查询

时间:2020-08-26 07:58:50

标签: node.js mongodb mongoose

我正在尝试将一个新文档保存到一个集合中,并同时更新两个不同集合中的两个其他文档:

const newApplication = new ApplicationSchema({...})
newApplication.save()

EventSchema.findByIdAndUpdate(event_id, { $inc: { "application_counts": 1 } })

EventOwnerSchema.findByIdAndUpdate(event_owner_id, { $dec: { "balance": ticketPrice } })

这些操作相互关联,如果其中任何一个失败,我想使所有这些操作都失败。一种可能的解决方案是,如果其中任何一个失败,则将它们链接起来并还原到以前的更新。

const newApplication = new ApplicationSchema({...})
newApplication.save((err, res_1) => {
  if(err) {
    return false;
  }
  EventSchema.findByIdAndUpdate(event_id, { $inc: { "application_counts": 1 } }, (err, res_2) => {
    if(err) {
      ApplicationSchema.deleteOne({_id: res_1._id})
      return false;
    }
    EventOwnerSchema.findByIdAndUpdate(event_owner_id, { $dec: { "balance": ticketPrice } }, (err, res_3) => {
      if(err) {
        ApplicationSchema.deleteOne({_id: res_1._id})
        EventSchema.findByIdAndUpdate(event_id, { $dec: { "application_counts": 1 } })
        return false;
      }
      return true;
    })
  })
})

但是,此解决方案对于性能而言并不理想(并且出于同样的原因,这个问题也存在,但我想我太挑剔了)。有什么建议吗?

编辑: 脚注:由于其他原因,我没有使用嵌入式文档。

1 个答案:

答案 0 :(得分:1)

交易就是要这样做的。 Mongoose Transactions

它允许您创建会话,执行一些操作以及中止/提交在会话中所做的更改。

myObj['a'] = x

感谢评论@Thomas Bormans