Sha256: 973fd5e33b235e2d664369ca60829761748d8f1be37d354310e6df14a67d8b3e

Contents?: true

Size: 1.53 KB

Versions: 26

Compression:

Stored size: 1.53 KB

Contents

# frozen_string_literal: true
# encoding: utf-8

module Mongoid
  module Persistable

    # Defines behavior for persistence operations that upsert documents.
    #
    # @since 4.0.0
    module Upsertable

      # 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.
      #
      # @example Upsert the document.
      #   document.upsert
      #
      # @param [ Hash ] options The validation options.
      #
      # @return [ true ] True.
      #
      # @since 3.0.0
      def upsert(options = {})
        prepare_upsert(options) do
          collection.find(atomic_selector).update_one(
              as_attributes, upsert: true, session: _session)
        end
      end

      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.
      #
      # @return [ true, false ] If the operation succeeded.
      #
      # @since 4.0.0
      def prepare_upsert(options = {})
        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

Version data entries

26 entries across 26 versions & 2 rubygems

Version Path
mongoid-7.3.4 lib/mongoid/persistable/upsertable.rb
mongoid-7.1.11 lib/mongoid/persistable/upsertable.rb
mongoid-7.2.6 lib/mongoid/persistable/upsertable.rb
mongoid-7.3.3 lib/mongoid/persistable/upsertable.rb
mongoid-7.3.2 lib/mongoid/persistable/upsertable.rb
mongoid-7.2.5 lib/mongoid/persistable/upsertable.rb
mongoid-7.1.10 lib/mongoid/persistable/upsertable.rb
mongoid-7.1.9 lib/mongoid/persistable/upsertable.rb
mongoid-7.2.4 lib/mongoid/persistable/upsertable.rb
mongoid-7.3.1 lib/mongoid/persistable/upsertable.rb
tdiary-5.1.6 vendor/bundle/ruby/2.7.0/gems/mongoid-7.1.7/lib/mongoid/persistable/upsertable.rb
mongoid-7.3.0 lib/mongoid/persistable/upsertable.rb
mongoid-7.2.3 lib/mongoid/persistable/upsertable.rb
mongoid-7.1.8 lib/mongoid/persistable/upsertable.rb
mongoid-7.2.2 lib/mongoid/persistable/upsertable.rb
mongoid-7.2.1 lib/mongoid/persistable/upsertable.rb
mongoid-7.1.7 lib/mongoid/persistable/upsertable.rb
mongoid-7.2.0 lib/mongoid/persistable/upsertable.rb
mongoid-7.1.6 lib/mongoid/persistable/upsertable.rb
mongoid-7.1.5 lib/mongoid/persistable/upsertable.rb