为什么mongodb abortTransaction()无法正常工作?

时间:2019-03-21 07:27:25

标签: node.js database mongodb transactions

我想使用nodejs和mongodb进行简单的事务。但是我注意到abortTransaction()没有运行。首先,我将记录添加到数据库中。然后,我想调用abortTransaction()并取消操作。我的示例代码如下。怎么了期待您的帮助和评论。

app.js

'use strict';
 const { MongoClient } = require('mongodb');

  async function a(client, db){
let session = client.startSession();
try {
    await session.startTransaction();
    await db.collection('denemecoll').insertOne({a: 'aaaaa', b: 'bbbb', c: 'cccc'});
    console.log('insert yapıldı');
    console.log('transaction find sonucu', await db.collection('denemecoll').find({}).toArray());
    await new Promise(resolve => {
        setTimeout(() => {
            resolve(true);
        }, 3000);
    });

    await session.abortTransaction();
    await session.endSession();
    console.log('transaction iptal edildi');
} catch (e){
    console.log(e);
}
}

  async function b(client, db){
   setTimeout(async () => {
    console.log('transaction harici find ', await 
 db.collection('denemecoll').find({}).toArray());
}, 1000)
}

 async function init(){
let client = await MongoClient.connect('mongodb://localhost:27017', { 
useNewUrlParser: true });
let db = client.db('deneme');
await db.collection('denemecoll').deleteMany({});
a(client, db);
b(client, db);

setTimeout(async () => {
    console.log('abort ediltikten sonraki find ', await 
db.collection('denemecoll').find({}).toArray());
}, 5000)
}

init().then(x => console.log('ok'));

在操作中使用会话时,出现错误。

{ MongoError: Transaction numbers are only allowed on a replica set member or mongos
at /home/ali/nodejs/deneme/node_modules/mongodb-core/lib/connection/pool.js:581:63
at authenticateStragglers (/home/ali/nodejs/deneme/node_modules/mongodb-core/lib/connection/pool.js:504:16)
at Connection.messageHandler (/home/ali/nodejs/deneme/node_modules/mongodb-core/lib/connection/pool.js:540:5)
at emitMessageHandler (/home/ali/nodejs/deneme/node_modules/mongodb-core/lib/connection/connection.js:310:10)
at Socket.<anonymous> (/home/ali/nodejs/deneme/node_modules/mongodb-core/lib/connection/connection.js:453:17)
at Socket.emit (events.js:197:13)
at addChunk (_stream_readable.js:288:12)
at readableAddChunk (_stream_readable.js:269:11)
at Socket.Readable.push (_stream_readable.js:224:10)
at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:150:17)

0 个答案:

没有答案