Module: Mongoid::Criteria::Findable

Included in:
Mongoid::Criteria
Defined in:
lib/mongoid/criteria/findable.rb

Instance Method Summary collapse

Instance Method Details

#execute_or_raise(ids, multi) ⇒ Document+

Execute the criteria or raise an error if no documents found.

Examples:

Execute or raise

criteria.execute_or_raise(id)

Parameters:

  • args (Object)

    The arguments passed.

Returns:

Raises:

Since:

  • 2.0.0



18
19
20
21
22
# File 'lib/mongoid/criteria/findable.rb', line 18

def execute_or_raise(ids, multi)
  result = multiple_from_map_or_db(ids)
  check_for_missing_documents!(result, ids)
  multi ? result : result.first
end

#find(*args) ⇒ Array<Document>, Document

Find the matchind document(s) in the criteria for the provided ids.

Examples:

Find by an id.

criteria.find(Moped::BSON::ObjectId.new)

Find by multiple ids.

criteria.find([ Moped::BSON::ObjectId.new, Moped::BSON::ObjectId.new ])

Parameters:

Returns:

Since:

  • 1.0.0



37
38
39
40
41
# File 'lib/mongoid/criteria/findable.rb', line 37

def find(*args)
  ids = args.__find_args__
  raise_invalid if ids.any?(&:nil?)
  for_ids(ids).execute_or_raise(ids, args.multi_arged?)
end

#for_ids(ids) ⇒ Criteria

Adds a criterion to the Criteria that specifies an id that must be matched.

Examples:

Add a single id criteria.

criteria.for_ids([ 1 ])

Add multiple id criteria.

criteria.for_ids([ 1, 2 ])

Parameters:

  • ids (Array)

    The array of ids.

Returns:



54
55
56
57
58
59
60
61
# File 'lib/mongoid/criteria/findable.rb', line 54

def for_ids(ids)
  ids = mongoize_ids(ids)
  if ids.size > 1
    send(id_finder, { _id: { "$in" => ids }})
  else
    send(id_finder, { _id: ids.first })
  end
end

#from_map_or_dbDocument

Get the document from the identity map, and if not found hit the database.

Examples:

Get the document from the map or criteria.

criteria.from_map_or_db

Returns:

Since:

  • 2.2.1



72
73
74
75
76
77
78
# File 'lib/mongoid/criteria/findable.rb', line 72

def from_map_or_db
  id = extract_id
  id = klass.fields["_id"].mongoize(id) if id
  doc = IdentityMap.get(klass, id || selector_with_type_selection)
  return nil if doc == {}
  doc && doc.matches?(selector) ? doc : first
end

#multiple_from_map_or_db(ids) ⇒ Array<Document>

Get the documents from the identity map, and if not found hit the database.

Examples:

Get the documents from the map or criteria.

criteria.multiple_from_map_or_db(ids)

Parameters:

  • The (ids)

    searched ids.

Returns:

  • (Array<Document>)

    The found documents.



89
90
91
92
93
94
# File 'lib/mongoid/criteria/findable.rb', line 89

def multiple_from_map_or_db(ids)
  return entries if embedded?
  ids = mongoize_ids(ids)
  result = from_identity_map(ids)
  ids.empty? ? result : result + from_database(ids)
end