Skip to content

Commit

Permalink
mongodb: fix get pagination count
Browse files Browse the repository at this point in the history
MongoDatabase.get wasn't returning the right
number of pages and documents.

Since mongodb and connect-mongo upgrade all
documents were counted instead of counting only
the documents matching the filter.
  • Loading branch information
maxime-beguin committed Apr 12, 2022
1 parent fb816dd commit 74c660b
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 4 deletions.
2 changes: 1 addition & 1 deletion lib/storages/databases/mongodb/MongoDatabase.js
Original file line number Diff line number Diff line change
Expand Up @@ -412,7 +412,7 @@ MongoDatabase.prototype.get = function(collection, filter, fields, limit, page,
function(error, documents) {
if (error) return callback(error);

this.db.collection(collection).countDocuments(function(countError, count) {
this.db.collection(collection).countDocuments(filter, function(countError, count) {
if (countError) return callback(countError);

callback(null, documents || [], {
Expand Down
11 changes: 8 additions & 3 deletions tests/server/storages/MongoDatabase.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ describe('MongoDatabase', function() {

// Mock MongoDB Collection
collection = {
countDocuments: chai.spy(function(callback) {
countDocuments: chai.spy(function(filter, callback) {
callback(null, documents.length);
}),
find: chai.spy(function() {
Expand Down Expand Up @@ -928,10 +928,15 @@ describe('MongoDatabase', function() {
var expectedFilter = new ResourceFilter().equal('field', 'value');

collection.find = chai.spy(function(filter) {
assert.deepEqual(filter, MongoDatabase.buildFilter(expectedFilter), 'Wrong filter');
assert.deepEqual(filter, MongoDatabase.buildFilter(expectedFilter), 'Wrong find filter');
return cursor;
});

collection.countDocuments = chai.spy(function(filter, callback) {
assert.deepEqual(filter, MongoDatabase.buildFilter(expectedFilter), 'Wrong countDocuments filter');
callback(null, documents.length);
});

database.get(expectedCollection, expectedFilter, null, null, null, null, function(error, results, pagination) {
database.db.collection.should.have.been.called.exactly(2);
database.db.collection.should.have.been.called.with(expectedCollection);
Expand Down Expand Up @@ -1107,7 +1112,7 @@ describe('MongoDatabase', function() {
it('should execute callback with an error if counting documents failed', function(done) {
var expectedError = new Error('Something went wrong');

collection.countDocuments = chai.spy(function(callback) {
collection.countDocuments = chai.spy(function(filter, callback) {
callback(expectedError);
});

Expand Down

0 comments on commit 74c660b

Please sign in to comment.