mongodb/mongoid · error · ArgumentError

cannot translate # (# ) to a direction specification

Error message

cannot translate #{value.inspect} (#{value.class}) to a direction specification

What it means

Translator.to_direction converts sort specifications: Hashes, Numerics, and strings/symbols containing 'desc' are accepted. Any other object cannot be interpreted as a sort direction and raises this ArgumentError naming the offending value.

Solutions

  1. Pass 1/-1, a Hash, or an 'asc'/'desc' string/symbol as the direction
  2. Wrap custom direction objects into one of the accepted forms before ordering
Defensive patterns

Strategy: type-guard

When it happens

Trigger: Thrown at lib/mongoid/criteria/translator.rb:38 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/7db9d8c0625efc54. Report an issue: GitHub.

Appendix: source

Thrown at lib/mongoid/criteria/translator.rb:38

      #   Translator.to_direction("1")
      #   Translator.to_direction(-1)
      #   Translator.to_direction(score: { "$meta": "textScore" })
      #
      # @param [ Hash | Numeric | String | Symbol ] value The value to convert.
      #
      # @return [ Hash | Numeric ] The direction.
      def to_direction(value)
        case value
        when Hash
          value
        when Numeric
          value
        when String
          /desc/i.match?(value) ? -1 : 1
        when Symbol
          to_direction(value.to_s)
        else
          raise ArgumentError, "cannot translate #{value.inspect} (#{value.class}) to a direction specification"
        end
      end
    end
  end
end

View on GitHub (pinned to 0da0e23d71)