From fec4f15ab248e6bb462eec0f0b7eb41cc8519d1e Mon Sep 17 00:00:00 2001 From: Matt Broadstone Date: Tue, 20 Aug 2019 10:59:36 -0400 Subject: [PATCH] fix(find): respect client-level provided read preference NODE-2124 --- lib/operations/find.js | 2 ++ test/functional/find_tests.js | 42 +++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/lib/operations/find.js b/lib/operations/find.js index a8b4d68720..6838213c32 100644 --- a/lib/operations/find.js +++ b/lib/operations/find.js @@ -3,6 +3,7 @@ const OperationBase = require('./operation').OperationBase; const Aspect = require('./operation').Aspect; const defineAspects = require('./operation').defineAspects; +const resolveReadPreference = require('../utils').resolveReadPreference; class FindOperation extends OperationBase { constructor(collection, ns, command, options) { @@ -10,6 +11,7 @@ class FindOperation extends OperationBase { this.ns = ns; this.cmd = command; + this.readPreference = resolveReadPreference(collection, this.options); } execute(server, callback) { diff --git a/test/functional/find_tests.js b/test/functional/find_tests.js index 25b4da89ca..fda172c6aa 100644 --- a/test/functional/find_tests.js +++ b/test/functional/find_tests.js @@ -3,6 +3,7 @@ const test = require('./shared').assert; const setupDatabase = require('./shared').setupDatabase; const expect = require('chai').expect; const Buffer = require('safe-buffer').Buffer; +const sinon = require('sinon'); describe('Find', function() { before(function() { @@ -3121,4 +3122,45 @@ describe('Find', function() { }); } }); + + it('should respect client-level read preference', { + metadata: { requires: { topology: ['replicaset'] } }, + + test: function(done) { + const config = this.configuration; + const client = config.newClient({}, { monitorCommands: true, readPreference: 'secondary' }); + + if (!config.usingUnifiedTopology()) { + this.skip(); + return; + } + + client.connect((err, client) => { + expect(err).to.not.exist; + + let selectedServer; + const selectServerStub = sinon.stub(client.topology, 'selectServer').callsFake(function() { + const args = Array.prototype.slice.call(arguments); + const originalCallback = args.pop(); + args.push((err, server) => { + selectedServer = server; + originalCallback(err, server); + }); + + return client.topology.selectServer.wrappedMethod.apply(this, args); + }); + + const collection = client.db().collection('test_read_preference'); + collection.find().toArray(err => { + expect(err).to.not.exist; + expect(selectedServer.description.type).to.eql('RSSecondary'); + + client.close(err => { + selectServerStub.restore(); + done(err); + }); + }); + }); + } + }); });