Module: Mongoid::Document

Extended by:
ActiveSupport::Concern
Includes:
Composable
Defined in:
lib/mongoid/document.rb,
lib/mongoid/railties/document.rb

Overview

This is the base module for all domain objects that need to be persisted to the database as documents.

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

ILLEGAL_KEY =

Regex for matching illegal BSON keys. Note that bson 4.1 has the constant BSON::String::ILLEGAL_KEY that should be used instead. When ruby driver 2.3.0 is released and Mongoid can be updated to require >= 2.3.0, the BSON constant can be used.

Since:

  • 6.0.0

/(\A[$])|(\.)/.freeze

Constants included from Composable

Composable::MODULES, Composable::RESERVED_METHOD_NAMES

Constants included from Interceptable

Interceptable::CALLBACKS

Constants included from Persistable

Persistable::LIST_OPERATIONS

Constants included from Matchable

Matchable::MATCHERS

Constants included from Fields

Fields::IDS, Fields::TYPE_MAPPINGS

Constants included from Atomic

Atomic::UPDATES

Instance Attribute Summary collapse

Attributes included from Stateful

#destroyed, #flagged_for_destroy

Attributes included from Relations

#__metadata

Attributes included from Attributes

#attributes

Instance Method Summary collapse

Methods included from Composable

prohibited_methods

Methods included from Equality

#<=>, #==, #===, #eql?

Methods included from Copyable

#clone

Methods included from Interceptable

#callback_executable?, #in_callback_state?, #run_after_callbacks, #run_before_callbacks, #run_callbacks

Methods included from Validatable

#begin_validate, #exit_validate, #performing_validations?, #read_attribute_for_validation, #valid?, #validated?, #validating_with_query?

Methods included from Traversable

#_children, #_parent, #_parent=, #_reset_memoized_children!, #_root, #_root?, #collect_children, #flag_children_persisted, #hereditary?, #parentize, #remove_child, #reset_persisted_children

Methods included from Cacheable

#cache_key

Methods included from Stateful

#destroyed?, #flagged_for_destroy?, #new_record?, #persisted?, #pushable?, #readonly?, #settable?, #updateable?

Methods included from Shardable

#shard_key_fields, #shard_key_selector

Methods included from Serializable

#serializable_hash

Methods included from Selectable

#atomic_selector

Methods included from Reloadable

#reload

Methods included from Relations

#embedded?, #embedded_many?, #embedded_one?, #metadata_name, #referenced_many?, #referenced_one?, #reload_relations

Methods included from Relations::CounterCache

#reset_counters

Methods included from Relations::Touchable

#touch

Methods included from Relations::Synchronization

#remove_inverse_keys, #syncable?, #synced, #synced?, #update_inverse_keys

Methods included from Relations::Reflections

#reflect_on_all_associations, #reflect_on_association

Methods included from Relations::Macros

#associations

Methods included from Relations::Cascading

#cascade!

Methods included from Relations::AutoSave

#__autosaving__, #autosaved?, #changed_for_autosave?

Methods included from Relations::Accessors

#__build__, #create_relation, #reset_relation_criteria, #set_relation

Methods included from Persistable

#atomically, #fail_due_to_callback!, #fail_due_to_validation!, #hasherizer

Methods included from Persistable::Unsettable

#unset

Methods included from Persistable::Upsertable

#upsert

Methods included from Persistable::Updatable

#update, #update!, #update_attribute

Methods included from Persistable::Settable

#set

Methods included from Persistable::Savable

#save, #save!

Methods included from Persistable::Renamable

#rename

Methods included from Persistable::Pushable

#add_to_set, #push

Methods included from Persistable::Pullable

#pull, #pull_all

Methods included from Positional

#positionally

Methods included from Persistable::Poppable

#pop

Methods included from Persistable::Logical

#bit

Methods included from Persistable::Incrementable

#inc

Methods included from Persistable::Destroyable

#destroy, #destroy!

Methods included from Persistable::Deletable

#delete

Methods included from Persistable::Creatable

#insert

Methods included from Matchable

matcher, #matches?

Methods included from Inspectable

#inspect

Methods included from Fields

#apply_default, #apply_defaults, #apply_post_processed_defaults, #apply_pre_processed_defaults, #attribute_names, #database_field_name, #lazy_settable?, option, options, #using_object_ids?

Methods included from Evolvable

#__evolve_object_id__

Methods included from Attributes

#assign_attributes, #attribute_missing?, #attribute_present?, #attributes_before_type_cast, #has_attribute?, #has_attribute_before_type_cast?, #read_attribute, #read_attribute_before_type_cast, #remove_attribute, #write_attribute, #write_attributes

Methods included from Attributes::Readonly

#attribute_writable?

Methods included from Attributes::Processing

#process_attributes

Methods included from Clients

clear, clients, default, disconnect, set, with_name

Methods included from Clients::Options

#collection, #collection_name, #mongo_client, #persistence_context, #with

Methods included from Changeable

#changed, #changed?, #changed_attributes, #changes, #children_changed?, #move_changes, #post_persist, #previous_changes, #remove_change, #setters

Methods included from Atomic

#add_atomic_pull, #add_atomic_unset, #atomic_array_add_to_sets, #atomic_array_pulls, #atomic_array_pushes, #atomic_attribute_name, #atomic_delete_modifier, #atomic_insert_modifier, #atomic_path, #atomic_paths, #atomic_position, #atomic_pulls, #atomic_pushes, #atomic_sets, #atomic_unsets, #atomic_updates, #delayed_atomic_pulls, #delayed_atomic_sets, #delayed_atomic_unsets, #flag_as_destroyed, #flagged_destroys, #process_flagged_destroys

Instance Attribute Details

#__selected_fieldsObject

Returns the value of attribute __selected_fields.



27
28
29
# File 'lib/mongoid/document.rb', line 27

def __selected_fields
  @__selected_fields
end

#new_recordObject (readonly)

Returns the value of attribute new_record.



28
29
30
# File 'lib/mongoid/document.rb', line 28

def new_record
  @new_record
end

Instance Method Details

#_destroyObject

Used in conjunction with fields_for to build a form element for the destruction of this association. Always returns false because Mongoid only supports immediate deletion of associations.

See ActionView::Helpers::FormHelper::fields_for for more info.



8
9
10
# File 'lib/mongoid/railties/document.rb', line 8

def _destroy
  false
end

#as_documentHash

Return a hash of the entire document hierarchy from this document and below. Used when the attributes are needed for everything and not just the current document.

Examples:

Get the full hierarchy.

person.as_document

Returns:

  • (Hash)

    A hash of all attributes in the hierarchy.

Since:

  • 1.0.0



174
175
176
# File 'lib/mongoid/document.rb', line 174

def as_document
  BSON::Document.new(as_attributes)
end

#as_json(options = nil) ⇒ Hash

Calls #as_json on the document with additional, Mongoid-specific options.

Examples:

Get the document as json.

document.as_json(compact: true)

Parameters:

  • options (Hash) (defaults to: nil)

    The options.

Options Hash (options):

  • :compact (true, false)

    Whether to include fields with nil values in the json document.

Returns:

  • (Hash)

    The document as json.

Since:

  • 5.1.0



191
192
193
194
195
196
197
# File 'lib/mongoid/document.rb', line 191

def as_json(options = nil)
  if options && (options[:compact] == true)
    super(options).reject! { |k,v| v.nil? }
  else
    super(options)
  end
end

#becomes(klass) ⇒ Document

Returns an instance of the specified class with the attributes, errors, and embedded documents of the current document.

Examples:

Return a subclass document as a superclass instance.

manager.becomes(Person)

Parameters:

  • klass (Class)

    The class to become.

Returns:

  • (Document)

    An instance of the specified class.

Raises:

  • (ArgumentError)

    If the class doesn’t include Mongoid::Document

Since:

  • 2.0.0



212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
# File 'lib/mongoid/document.rb', line 212

def becomes(klass)
  unless klass.include?(Mongoid::Document)
    raise ArgumentError, "A class which includes Mongoid::Document is expected"
  end

  became = klass.new(clone_document)
  became._id = _id
  became.instance_variable_set(:@changed_attributes, changed_attributes)
  became.instance_variable_set(:@errors, ActiveModel::Errors.new(became))
  became.errors.instance_variable_set(:@messages, errors.instance_variable_get(:@messages))
  became.instance_variable_set(:@new_record, new_record?)
  became.instance_variable_set(:@destroyed, destroyed?)
  became.changed_attributes["_type"] = self.class.to_s
  became._type = klass.to_s

  # mark embedded docs as persisted
  embedded_relations.each_pair do |name, meta|
    without_autobuild do
      relation = became.__send__(name)
      Array.wrap(relation).each do |r|
        r.instance_variable_set(:@new_record, new_record?)
      end
    end
  end

  became
end

#freezeDocument

Freezes the internal attributes of the document.

Examples:

Freeze the document

document.freeze

Returns:

Since:

  • 2.0.0



51
52
53
# File 'lib/mongoid/document.rb', line 51

def freeze
  as_attributes.freeze and self
end

#frozen?true, false

Checks if the document is frozen

Examples:

Check if frozen

document.frozen?

Returns:

  • (true, false)

    True if frozen, else false.

Since:

  • 2.0.0



63
64
65
# File 'lib/mongoid/document.rb', line 63

def frozen?
  attributes.frozen?
end

#hashInteger

Delegates to identity in order to allow two records of the same identity to work with something like:

[ Person.find(1), Person.find(2), Person.find(3) ] &
[ Person.find(1), Person.find(4) ] # => [ Person.find(1) ]

Examples:

Get the hash.

document.hash

Returns:

  • (Integer)

    The hash of the document’s identity.

Since:

  • 1.0.0



79
80
81
# File 'lib/mongoid/document.rb', line 79

def hash
  identity.hash
end

#identityArray

A Document’s is identified absolutely by its class and database id:

Person.first.identity #=> [Person, BSON::ObjectId(‘4f775130a04745933a000003’)]

Examples:

Get the identity

document.identity

Returns:

  • (Array)

    An array containing [document.class, document._id]

Since:

  • 3.0.0



93
94
95
# File 'lib/mongoid/document.rb', line 93

def identity
  [ self.class, self._id ]
end

#initialize(attrs = nil) ⇒ Document

Instantiate a new Document, setting the Document’s attributes if given. If no attributes are provided, they will be initialized with an empty Hash.

If a primary key is defined, the document’s id will be set to that key, otherwise it will be set to a fresh BSON::ObjectId string.

Examples:

Create a new document.

Person.new(:title => "Sir")

Parameters:

  • attrs (Hash) (defaults to: nil)

    The attributes to set up the document with.

Returns:

Since:

  • 1.0.0



112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/mongoid/document.rb', line 112

def initialize(attrs = nil)
  _building do
    @new_record = true
    @attributes ||= {}
    apply_pre_processed_defaults
    apply_default_scoping
    process_attributes(attrs) do
      yield(self) if block_given?
    end
    apply_post_processed_defaults
    # @todo: #2586: Need to have access to parent document in these
    #   callbacks.
    run_callbacks(:initialize) unless _initialize_callbacks.empty?
  end
end

#model_nameString

Return the model name of the document.

Examples:

Return the model name.

document.model_name

Returns:

  • (String)

    The model name.

Since:

  • 3.0.16



136
137
138
# File 'lib/mongoid/document.rb', line 136

def model_name
  self.class.model_name
end

#to_aArray<Document>

Return an array with this Document only in it.

Examples:

Return the document in an array.

document.to_a

Returns:

  • (Array<Document>)

    An array with the document as its only item.

Since:

  • 1.0.0



160
161
162
# File 'lib/mongoid/document.rb', line 160

def to_a
  [ self ]
end

#to_keyString

Return the key value for the document.

Examples:

Return the key.

document.to_key

Returns:

  • (String)

    The id of the document or nil if new.

Since:

  • 2.4.0



148
149
150
# File 'lib/mongoid/document.rb', line 148

def to_key
  (persisted? || destroyed?) ? [ id.to_s ] : nil
end