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

Errors::DocumentNotFound.new(klass, nil, nil)

Error message

Errors::DocumentNotFound.new(klass, nil, nil)

What it means

Raised by the private raise_document_not_found_error in Mongoid::Contextual::None. The None context is returned for criteria that can never match (e.g. Mongoid.none / Model.none), so any find/first-style call that requires a document always raises DocumentNotFound with nil id/ids — a sentinel error representing guaranteed emptiness.

Solutions

  1. Check criteria.exists?/any? before bang queries on possibly-null criteria
  2. Rescue Mongoid::Errors::DocumentNotFound for optional-document flows
Defensive patterns

Strategy: try-catch

When it happens

Trigger: Thrown at lib/mongoid/contextual/none.rb:327 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/009b50bb11f9282e. Report an issue: GitHub.

Appendix: source

Thrown at lib/mongoid/contextual/none.rb:327

      # Always returns zero.
      #
      # @example Get the length of null context.
      #   context.length
      #
      # @return [ Integer ] Always zero.
      def length
        entries.length
      end
      alias size length

      alias find_first first
      alias one first

      private

      def raise_document_not_found_error
        raise Errors::DocumentNotFound.new(klass, nil, nil)
      end
    end
  end
end

View on GitHub (pinned to 0da0e23d71)