Mongoid returning the wrong count of documents

35 views Asked by At

Mongoid 8.1.4 on latest MongoDB, I'm using pagy to paginate (which doesn't work out of the box, but can be fixed by overriding a method).

My overriding:

module PagyExtension
  module Mongoid
    def pagy_get_vars(collection, vars)
      vars[:count] = collection.count
      super
    end
  end
end

Pagy::Backend.prepend PagyExtension::Mongoid

(Mongoid doesn't like AR count(:all)) Everything appears to work, just not counting.

A spec to simplify the problem:

context "when paginating" do
  let(:params) do
    {
      "page" => 1,
      "per_page" => 20,
      "state" => "created"
    }
  end
  let!(:documents) { create_list(:document, 25) }

  it "returns paginated documents" do
    expect(result.value[:records].to_a.count).to eq(20)
    expect(result.value[:records].count).to eq(20)
  end
end

First expectation passes (there are actually 20 documents in records, second one fails, the method count returns "25". Extremely confused by this, I can inspect result.value[:records] and see there are 20 documents, I have no idea why count returns 25.

0

There are 0 answers