Module: Mongoid::Persistable::Upsertable
Relationships & Source Files | |
Extension / Inclusion / Inheritance Descendants | |
Included In:
| |
Defined in: | lib/mongoid/persistable/upsertable.rb |
Overview
Defines behavior for persistence operations that upsert documents.
Instance Method Summary
-
#upsert(options = {}) ⇒ true
Perform an upsert of the document.
-
#prepare_upsert(options = {}) ⇒ true | false
private
Internal use only
Internal use only
Prepare the upsert for execution.
Instance Method Details
#prepare_upsert(options = {}) ⇒ true
| false
(private)
This method is for internal use only.
Prepare the upsert for execution.
# File 'lib/mongoid/persistable/upsertable.rb', line 71
def prepare_upsert( = {}) raise Errors::ReadonlyDocument.new(self.class) if readonly? && !Mongoid.legacy_readonly return false if performing_validations?( ) && invalid?(:upsert) result = run_callbacks(:upsert) do yield(self) true end self.new_record = false post_process_persist(result, ) and result end
#upsert(options = {}) ⇒ true
Perform an upsert of the document. If the document does not exist in the database, then Mongo will insert a new one, otherwise the fields will get overwritten with new values on the existing document.
If the replace option is true, unspecified attributes will be dropped, and if it is false, unspecified attributes will be maintained. The replace option defaults to false in ::Mongoid
9.
# File 'lib/mongoid/persistable/upsertable.rb', line 36
def upsert( = {}) prepare_upsert( ) do if [:replace] if [:set_on_insert] raise ArgumentError, "cannot specify :set_on_insert with `replace: true`" end collection.find(atomic_selector).replace_one( as_attributes, upsert: true, session: _session) else attrs = { "$set" => as_attributes } attrs["$setOnInsert"] = [:set_on_insert] if [:set_on_insert] collection.find(atomic_selector).update_one( attrs, upsert: true, session: _session) end end end