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
Raised by Persistable::Upsertable#upsert when both replace: true and a :set_on_insert hash are passed. A replace upsert overwrites the whole document on insert, so there is nothing to apply set_on_insert to; the conflicting options combination is rejected as an ArgumentError.
Solutions
- Remove :set_on_insert when using replace: true
- Drop replace: true if per-insert attributes are needed
Defensive patterns
Strategy: validation
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.
Appendix: 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)