Skip to content

Commit

Permalink
fix(collection): countDocuments throws error when query doesn't match…
Browse files Browse the repository at this point in the history
… docs

The countDocuments method was not properly checking that documents were
returned from the query. Added tests on top of astanciu's bug fix.

Fixes NODE-1543
  • Loading branch information
rweinberger authored and mbroadst committed Jul 5, 2018
1 parent b8b4bfa commit 4e83556
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/operations/collection_ops.js
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ function countDocuments(coll, query, options, callback) {
if (err) return handleCallback(callback, err);
result.toArray((err, docs) => {
if (err) handleCallback(err);
handleCallback(callback, null, docs[0].n);
handleCallback(callback, null, docs.length ? docs[0].n : 0);
});
});
}
Expand Down
35 changes: 35 additions & 0 deletions test/functional/collection_tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
const test = require('./shared').assert;
const setupDatabase = require('./shared').setupDatabase;
const expect = require('chai').expect;
const MongoClient = require('../..').MongoClient;

describe('Collection', function() {
before(function() {
Expand Down Expand Up @@ -1581,6 +1582,40 @@ describe('Collection', function() {
}
});

it('should correctly perform estimatedDocumentCount on non-matching query', function(done) {
const configuration = this.configuration;
const client = new MongoClient(configuration.url(), { w: 1 });

client.connect(function(err, client) {
const db = client.db(configuration.db);
const collection = db.collection('nonexistent_coll_1');
const close = e => client.close(() => done(e));

Promise.resolve()
.then(() => collection.estimatedDocumentCount({ a: 'b' }))
.then(count => expect(count).to.equal(0))
.then(() => close())
.catch(e => close(e));
});
});

it('should correctly perform countDocuments on non-matching query', function(done) {
const configuration = this.configuration;
const client = new MongoClient(configuration.url(), { w: 1 });

client.connect(function(err, client) {
const db = client.db(configuration.db);
const collection = db.collection('nonexistent_coll_2');
const close = e => client.close(() => done(e));

Promise.resolve()
.then(() => collection.countDocuments({ a: 'b' }))
.then(count => expect(count).to.equal(0))
.then(() => close())
.catch(e => close(e));
});
});

describe('Retryable Writes on bulk ops', function() {
const MongoClient = require('../../lib/mongo_client');

Expand Down

0 comments on commit 4e83556

Please sign in to comment.