Search code examples
javascriptnode.jsmongodbmongoose

Mongoose Transactions and Post Transactional Operations


I am using mongoose together with sessions to perform ACID transactions in our nodejs + express backend.

lately, I have a necessity to send a message to one of our workers (backed by RabbitMQ) to make post transactional operation. I cannot directly send the message to our worker after the commit because there is a complex workflow behind it and completing the transaction does not always mean that the code must be called.

I believe that I need to use event emitters to register .once('onCommit', ...) event, and call emit('onCommit') when the transaction is done. But this is manual approach.

I would like to know if there is out of the box support in mongoose to make post transactional operations using mongoose.ClientSession. I am seeing that mongoose sessions are by itself Event Listeners but I couldn't find any related docuementation. I guess session events are for internal use.

can anyone enlighten me?

thank you


Solution

  • You should be able to use ended event. So below code should work if you finalize the transaction operation with session.endSession();

    session.on('ended', () => 'post transaction operation');
    

    Additionally if you need an information about transaction committed or aborted. You can get the post session data and check transaction state like below:

    session.on('ended', (postSession) => {
        const state = postSession.transaction.state;
    
        if (state === 'TRANSACTION_COMMITTED') {
          // successful transaction operation
        }
    
        if (state === 'TRANSACTION_ABORTED') {
          // aborted transaction operation
        }
     });