繁体   English   中英

mongodb nodejs 驱动事务

[英]mongodb nodejs driver transactions

在书籍集合中插入数据时,我强行在代码中出错,以便我可以检查事务在 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 )
} )
  1. 您需要一个复制集来使用 mongodb 的事务
  2. 您需要在所有写入操作的选项中路径session
const MongoClient = require( 'mongodb' ).MongoClient;
const URL = "mongodb://localhost:27017/testapp?rs=myreplicaset"

MongoClient.connect( URL, {
    useNewUrlParser: true,
    useUnifiedTopology: true
} )
.then( async 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"
        } , {session})

        await db.collection( 'book' ).insertOne( {
            user_id: info.ops[ 0 ]._id,
            booked: true,
            asdf
        } , {session})

        await session.commitTransaction()

    } catch ( e ) {
        await session.abortTransaction()
        console.log( e.message )
    } finally {
        session.endSession()
        client.close()
    }
} )
.catch( err => {
    console.log( err )
} )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM