mongodb/mongoid · error · ArgumentError

cannot specify :set_on_insert with `replace: true`

Error message

cannot specify :set_on_insert with `replace: true`

What it means

Error "cannot specify :set_on_insert with `replace: true`" thrown in mongodb/mongoid.

Source

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

      # @example Upsert the document with replace.
      #   document.upsert(replace: true)
      #
      # @example Upsert with extra attributes to use when inserting.
      #   document.upsert(set_on_insert: { created_at: DateTime.now })
      #
      # @param [ Hash ] options The validation options.
      #
      # @option options [ true | false ] :validate Whether or not to validate.
      # @option options [ true | false ] :replace Whether or not to replace
      #   the document on upsert.
      # @option options [ Hash ] :set_on_insert The attributes to include if
      #   the document does not already exist.
      #
      # @return [ true ] True.
      def upsert(options = {})
        prepare_upsert(options) do
          if options[:replace]
            raise ArgumentError, 'cannot specify :set_on_insert with `replace: true`' if options[:set_on_insert]

            collection.find(atomic_selector).replace_one(
              as_attributes, upsert: true, session: _session
            )
          else
            attrs = { '$set' => as_attributes }
            attrs['$setOnInsert'] = options[:set_on_insert] if options[:set_on_insert]

            collection.find(atomic_selector).update_one(
              attrs, upsert: true, session: _session
            )
          end
        end
      end

      private

      # Prepare the upsert for execution.

View on GitHub (pinned to 0da0e23d71)

When it happens

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