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

When adding a(n) %{klass} to %{base}#%{name}, Mongoid could

Error message

When adding a(n) %{klass} to %{base}#%{name}, Mongoid could not determine the inverse foreign key to set. The attempted key was '%{inverse}'.

What it means

Error "When adding a(n) %{klass} to %{base}#%{name}, Mongoid could not determine the inverse foreign key to set. The attempted key was '%{inverse}'." thrown in mongodb/mongoid.

Source

Thrown at lib/mongoid/association/referenced/has_one/buildable.rb:42

            if query?(object)
              # Handle array of hashes from $lookup aggregation
              if object.is_a?(Array) && object.all? { |o| o.is_a?(Hash) }
                doc = object.first
                return doc ? Factory.execute_from_db(klass, doc, nil, selected_fields, execute_callbacks: false) : nil
              end

              execute_query(object, base) unless base.new_record?
            else
              clear_associated(object)
              object
            end
          end

          private

          def clear_associated(object)
            unless inverse
              raise Errors::InverseNotFound.new(
                @owner_class,
                name,
                object.class,
                foreign_key
              )
            end
            if object && (associated = object.send(inverse))
              associated.substitute(nil)
            end
          end

          def query_criteria(object, base)
            crit = klass.criteria
            crit = crit.apply_scope(scope)
            crit = crit.where(foreign_key => object)
            with_polymorphic_criterion(crit, base)
          end

View on GitHub (pinned to 0da0e23d71)

When it happens

Trigger: Thrown at lib/mongoid/association/referenced/has_one/buildable.rb:42 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/ea6e0fcce111cdbc. Report an issue: GitHub.