mongodb/mongoid · error · Mongoid::Errors::TransactionError

Transaction failed with the following error

Error message

Transaction failed with the following error: %{error}.

What it means

transaction wraps the block in session.with_transaction and re-raises failures inside the transaction (write errors, conflicts, aborts) as TransactionError with the original message. It signals the transaction body failed and was aborted.

Solutions

  1. Inspect the wrapped error message to find and fix the root cause
  2. Rescue Mongoid::Errors::TransactionError and retry on transient failures such as write conflicts
Defensive patterns

Strategy: try-catch

When it happens

Trigger: Thrown at lib/mongoid/clients/sessions.rb:95 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of mongodb/mongoid@0da0e23d71 (2026-08-23). Data as JSON: /api/errors/779cf68c2bd85468. Report an issue: GitHub.

Appendix: source

Thrown at lib/mongoid/clients/sessions.rb:95

        # @raise [ Mongoid::Errors::TransactionsNotSupported ] If MongoDB deployment
        #   the client is connected to does not support transactions.
        # @raise [ Mongoid::Errors::TransactionError ] If there is an error raised
        #   by MongoDB deployment or MongoDB driver.
        #
        # @yield Provided block will be executed inside a transaction.
        def transaction(options = {}, session_options: {}, &block)
          with_session(session_options) do |session|
            session.with_transaction(options, &block).tap { run_commit_callbacks(session) }
          rescue *transactions_not_supported_exceptions
            raise Mongoid::Errors::TransactionsNotSupported
          rescue Mongoid::Errors::Rollback
            run_abort_callbacks(session)
          rescue Mongoid::Errors::InvalidSessionNesting
            # Session should be ended here.
            raise Mongoid::Errors::InvalidTransactionNesting.new
          rescue Mongo::Error::InvalidSession, Mongo::Error::InvalidTransactionOperation => e
            run_abort_callbacks(session)
            raise Mongoid::Errors::TransactionError.new(e)
          rescue StandardError => e
            run_abort_callbacks(session)
            raise e
          end
        end

        # Sets up a callback is called after a commit of a transaction.
        # The callback is called only if the document is created, updated, or destroyed
        # in the transaction.
        #
        # See +ActiveSupport::Callbacks::ClassMethods::set_callback+ for more
        # information about method parameters and possible options.
        def after_commit(*args, &block)
          set_options_for_callbacks!(args)
          set_callback(:commit, :after, *args, &block)
        end

        # Shortcut for +after_commit :hook, on: [ :create, :update ]+

View on GitHub (pinned to 0da0e23d71)