【问题标题】:mongodb nodejs driver transactionsmongodb nodejs驱动事务
【发布时间】: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


    【解决方案1】:
    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 )
    } )
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-03
      • 2021-06-05
      • 1970-01-01
      相关资源
      最近更新 更多