Skip to content

Commit

Permalink
MONGOID-5647 Allow #count to be used with #for_js (#5693) (#5696)
Browse files Browse the repository at this point in the history
* MONGOID-5647 Allow #count to be used with #for_js

* look for $where in nested hashes

* fix typo in method name
  • Loading branch information
jamis authored Aug 29, 2023
1 parent 384c03a commit b603a2b
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
27 changes: 26 additions & 1 deletion lib/mongoid/contextual/mongo.rb
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,14 @@ def cached?
# @return [ Integer ] The number of matches.
def count(options = {}, &block)
return super(&block) if block_given?
try_cache(:count) { view.count_documents(options) }

try_cache(:count) do
if valid_for_count_documents?
view.count_documents(options)
else
view.count(options)
end
end
end

# Get the estimated number of documents matching the query.
Expand Down Expand Up @@ -902,6 +909,24 @@ def process_raw_docs(raw_docs, limit)
docs = eager_load(docs)
limit ? docs : docs.first
end

# Queries whether the current context is valid for use with
# the #count_documents? predicate. A context is valid if it
# does not include a `$where` operator.
#
# @return [ true | false ] whether or not the current context
# excludes a `$where` operator.
def valid_for_count_documents?(hash = view.filter)
# Note that `view.filter` is a BSON::Document, and all keys in a
# BSON::Document are strings; we don't need to worry about symbol
# representations of `$where`.
hash.keys.each do |key|
return false if key == '$where'
return false if hash[key].is_a?(Hash) && !valid_for_count_documents?(hash[key])
end

true
end
end
end
end
10 changes: 10 additions & 0 deletions spec/mongoid/contextual/mongo_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,16 @@
end
end
end

context 'when for_js is present' do
let(:context) do
Band.for_js('this.name == "Depeche Mode"')
end

it 'counts the expected records' do
expect(context.count).to eq(1)
end
end
end

describe "#estimated_count" do
Expand Down

0 comments on commit b603a2b

Please sign in to comment.