【发布时间】:2019-12-05 15:04:13
【问题描述】:
在书籍集合中插入数据时,我在代码中强制出错,以便我可以检查事务在 mongodb 节点驱动程序中是否正常工作,但是当我运行此代码时,没有发生回滚。它在用户集合中创建一个文档,然后抛出错误但中止不起作用。
const MongoClient = require( 'mongodb' ).MongoClient;
const URL = "mongodb://localhost:27017/testapp"
MongoClient.connect( URL, {
useNewUrlParser: true,
useUnifiedTopology: true
} )
.then( async client => {
_client = client
let _db = client.db( 'testapp' );
let session = _client.startSession()
session.startTransaction()
try {
let info = await _db.collection( 'user' ).insertOne( {
name: "Anik",
position: "Full Stack"
} )
await _db.collection( 'book' ).insertOne( {
user_id: info.ops[ 0 ]._id,
booked: true,
asdf
} )
await session.commitTransaction()
session.endSession()
_client.close()
} catch ( e ) {
await session.abortTransaction()
session.endSession()
_client.close()
console.log( e.message )
}
} )
.catch( err => {
console.log( err )
} )
【问题讨论】:
标签: node.js mongodb transactions nosql