Skip to content

Commit 09c7d8e

Browse files
authored
fix(collection): countDocuments throws error when query doesn't match 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
1 parent 61c07fd commit 09c7d8e

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

lib/operations/collection_ops.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -234,7 +234,7 @@ function countDocuments(coll, query, options, callback) {
234234
if (err) return handleCallback(callback, err);
235235
result.toArray((err, docs) => {
236236
if (err) handleCallback(err);
237-
handleCallback(callback, null, docs[0].n);
237+
handleCallback(callback, null, docs.length ? docs[0].n : 0);
238238
});
239239
});
240240
}

test/functional/collection_tests.js

+35
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
const test = require('./shared').assert;
33
const setupDatabase = require('./shared').setupDatabase;
44
const expect = require('chai').expect;
5+
const MongoClient = require('../..').MongoClient;
56

67
describe('Collection', function() {
78
before(function() {
@@ -1581,6 +1582,40 @@ describe('Collection', function() {
15811582
}
15821583
});
15831584

1585+
it('should correctly perform estimatedDocumentCount on non-matching query', function(done) {
1586+
const configuration = this.configuration;
1587+
const client = new MongoClient(configuration.url(), { w: 1 });
1588+
1589+
client.connect(function(err, client) {
1590+
const db = client.db(configuration.db);
1591+
const collection = db.collection('nonexistent_coll_1');
1592+
const close = e => client.close(() => done(e));
1593+
1594+
Promise.resolve()
1595+
.then(() => collection.estimatedDocumentCount({ a: 'b' }))
1596+
.then(count => expect(count).to.equal(0))
1597+
.then(() => close())
1598+
.catch(e => close(e));
1599+
});
1600+
});
1601+
1602+
it('should correctly perform countDocuments on non-matching query', function(done) {
1603+
const configuration = this.configuration;
1604+
const client = new MongoClient(configuration.url(), { w: 1 });
1605+
1606+
client.connect(function(err, client) {
1607+
const db = client.db(configuration.db);
1608+
const collection = db.collection('nonexistent_coll_2');
1609+
const close = e => client.close(() => done(e));
1610+
1611+
Promise.resolve()
1612+
.then(() => collection.countDocuments({ a: 'b' }))
1613+
.then(count => expect(count).to.equal(0))
1614+
.then(() => close())
1615+
.catch(e => close(e));
1616+
});
1617+
});
1618+
15841619
describe('Retryable Writes on bulk ops', function() {
15851620
const MongoClient = require('../../lib/mongo_client');
15861621

0 commit comments

Comments
 (0)