Appearance
mongoose-transactions
简介
mongoose-transactions是一个mongoose插件,用于在mongoose中实现事务功能。
安装
bash
npm install mongoose-transactions --save示例
- 使用mongoose-transactions
javascript
const T = require('mongoose-transactions')
// 开启事务
const t = new T()
// 事务操作
try {
// 事务操作 User 模型名称
await t.insert('User', {name: 'John'}) // 插入
//User模型名称,更新条件,更新数据
await t.update('User', {name: 'John'}, {name: 'John Doe'}) // 更新
//User模型名称,删除条件
await t.remove('User', {name: 'John'}) // 删除
// 提交事务
await t.run()
} catch (error) {
// 回滚事务
await t.rollback()
}原生事务操作
js
const mongoose = require('mongoose')
const t = await mongoose.startSession()
t.startTransaction()
try {
await User.create([{name: 'John'}, {name: 'John Doe'}], { session: t })
await t.commitTransaction() // 提交事务
} catch (error) {
await t.abortTransaction() // 回滚事务
}
t.endSession() // 结束事务