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

Attempted to persist a readonly document of class '%{klass}'

Error message

Attempted to persist a readonly document of class '%{klass}'.

What it means

Error "Attempted to persist a readonly document of class '%{klass}'." thrown in mongodb/mongoid.

Source

Thrown at lib/mongoid/persistable/upsertable.rb:69

      private

      # Prepare the upsert for execution.
      #
      # @api private
      #
      # @example Prepare the upsert
      #   document.prepare_upsert do
      #     collection.find(selector).update(as_document)
      #   end
      #
      # @param [ Hash ] options The options hash.
      #
      # @option options [ true | false ] :validate Whether or not to validate.
      #
      # @return [ true | false ] If the operation succeeded.
      def prepare_upsert(options = {})
        raise Errors::ReadonlyDocument.new(self.class) if readonly? && !Mongoid.legacy_readonly
        return false if performing_validations?(options) && invalid?(:upsert)

        result = run_callbacks(:upsert) do
          yield(self)
          true
        end
        self.new_record = false
        post_process_persist(result, options) and result
      end
    end
  end
end

View on GitHub (pinned to 0da0e23d71)

When it happens

Trigger: Thrown at lib/mongoid/persistable/upsertable.rb:69 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/efdbe9966363f004. Report an issue: GitHub.