目标:我正在创建一个模拟交易,涉及在两个账户之间交换一定金额。 (使用NodeJS服务器和Mongoose)
| ACCOUNT1 | ACCOUNT2 | (Account Balance)
--------------------------------
T1.| 5000 | 2000 | (initial values)
--------------------------------
T2.| 3000 | 4000 | (ACCOUNT1 transfers 2000 to ACCOUNT2)
--------------------------------
问题:问题在于每个事务T1,T2都需要两个操作:
这两个中的任何一个失败都会导致其他
回滚当前的方法:
// save transaction log.then(function(data){
AccountHelper.updateAccount(accountOwner, fromAccount, amount)
.then(function(data){
AccountHelper.updateAccount(accountOwner, fromAccount, amount)
.then(function(data){
//some success response
}).catch(function(err){
// rollback the previous update
// respond with the err
});
})
.catch(function(err){
// respond with the err
});
//}).catch(function(err){ respond with the err});
有更好的方法吗?我能想到的另一种方法是:
事件发射器方式:
另请注意,任何交易都可以在将来的任何时间删除,必须反映在当前余额中(交易中涉及的金额必须恢复到原始账户)。
答案 0 :(得分:1)
一般来说,不要。正如mongoose-transact模块的作者雄辩地说,交易被排除在Mongodb之外是有原因的。