mongo-tx nodejs 的 mongodb 事务处理包 项目简介
一个灵活可扩展的 nodejs 的 mongodb 事务处理包,支持出错回滚,事务锁,单文档级锁,ODM 无关。import mongoTx from 'mongo-tx'
import createMongoModel from 'mongo-tx/lib/implements/create-mongo-model'
import createMongoLock from 'mongo-tx/lib/implements/create-mongo-lock'
const runTx = mongoTx({
createModel: createMongoModel({ db: nativeDb }),
createLock: createMongoLock({ db: nativeDb, wait: true }), // wait is true: wait until current release is release instead of throw an error
})
await runTx('some_transfer', async tx => {
const TxAccounts = tx.wrap('accounts')
const acc1 = await TxAccounts.findOne({name: 'u1'})
const acc2 = await TxAccounts.findOne({name: 'u2'})
await TxAccounts.findOneAndUpdate({
name: 'u1',
}, {
$set: {
money: acc1.money - 100,
},
})
throw new Error('Some error cause auto rollback!')
await TxAccounts.findOneAndUpdate({
name: 'u2',
}, {
$set: {
money: acc2.money + 100,
},
})
})
import createMongoModel from 'mongo-tx/lib/implements/create-mongo-model'
import createMongoLock from 'mongo-tx/lib/implements/create-mongo-lock'
const runTx = mongoTx({
createModel: createMongoModel({ db: nativeDb }),
createLock: createMongoLock({ db: nativeDb, wait: true }), // wait is true: wait until current release is release instead of throw an error
})
await runTx('some_transfer', async tx => {
const TxAccounts = tx.wrap('accounts')
const acc1 = await TxAccounts.findOne({name: 'u1'})
const acc2 = await TxAccounts.findOne({name: 'u2'})
await TxAccounts.findOneAndUpdate({
name: 'u1',
}, {
$set: {
money: acc1.money - 100,
},
})
throw new Error('Some error cause auto rollback!')
await TxAccounts.findOneAndUpdate({
name: 'u2',
}, {
$set: {
money: acc2.money + 100,
},
})
})