Module: Mongoid::CollectionConfigurable::ClassMethods

Defined in:
lib/mongoid/collection_configurable.rb

Instance Method Summary collapse

Instance Method Details

#create_collection(force: false) ⇒ Object

Create the collection for the called upon Mongoid model.

This method does not re-create existing collections.

If the document includes ‘store_in` macro with `collection_options` key,

these options are used when creating the collection.

Parameters:

  • force (true | false) (defaults to: false)

    If true, the method will drop existing collections before creating new ones. If false, the method will create only new collection (that do not exist in the database).

Raises:



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/mongoid/collection_configurable.rb', line 24

def create_collection(force: false)
  if collection_name.empty?
    # This is most probably an anonymous class, we ignore them.
    return
  end
  if collection_name.match(/^system\./)
    # We do not do anything with system collections.
    return
  end
  if force
    collection.drop
  end
  if coll_options = collection.database.list_collections(filter: { name: collection_name.to_s }).first
    if force
      raise Errors::DropCollectionFailure.new(collection_name)
    else
      logger.debug(
        "MONGOID: Collection '#{collection_name}' already exists " +
        "in database '#{database_name}' with options '#{coll_options}'."
      )
    end
  else
    begin
      collection.database[collection_name, storage_options.fetch(:collection_options, {})].create
    rescue Mongo::Error::OperationFailure => e
      raise Errors::CreateCollectionFailure.new(
        collection_name,
        storage_options[:collection_options],
        e
      )
    end
  end
end