Skip to content

Commit

Permalink
MONGOID-5647 Allow #count to be used with #for_js (#5693) (#5695)
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 committed Aug 29, 2023
1 parent 35d0c63 commit 45effff
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
25 changes: 24 additions & 1 deletion lib/mongoid/contextual/mongo.rb
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,12 @@ class Mongo
# @return [ Integer ] The number of matches.
def count(options = {}, &block)
return super(&block) if block_given?
view.count_documents(options)

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

# Get the estimated number of documents matching the query.
Expand Down Expand Up @@ -813,6 +818,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 @@ -158,6 +158,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 45effff

Please sign in to comment.