Skip to content

Commit fec4f15

Browse files
committed
fix(find): respect client-level provided read preference
NODE-2124
1 parent c18b4ba commit fec4f15

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

lib/operations/find.js

+2
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,15 @@
33
const OperationBase = require('./operation').OperationBase;
44
const Aspect = require('./operation').Aspect;
55
const defineAspects = require('./operation').defineAspects;
6+
const resolveReadPreference = require('../utils').resolveReadPreference;
67

78
class FindOperation extends OperationBase {
89
constructor(collection, ns, command, options) {
910
super(options);
1011

1112
this.ns = ns;
1213
this.cmd = command;
14+
this.readPreference = resolveReadPreference(collection, this.options);
1315
}
1416

1517
execute(server, callback) {

test/functional/find_tests.js

+42
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ const test = require('./shared').assert;
33
const setupDatabase = require('./shared').setupDatabase;
44
const expect = require('chai').expect;
55
const Buffer = require('safe-buffer').Buffer;
6+
const sinon = require('sinon');
67

78
describe('Find', function() {
89
before(function() {
@@ -3121,4 +3122,45 @@ describe('Find', function() {
31213122
});
31223123
}
31233124
});
3125+
3126+
it('should respect client-level read preference', {
3127+
metadata: { requires: { topology: ['replicaset'] } },
3128+
3129+
test: function(done) {
3130+
const config = this.configuration;
3131+
const client = config.newClient({}, { monitorCommands: true, readPreference: 'secondary' });
3132+
3133+
if (!config.usingUnifiedTopology()) {
3134+
this.skip();
3135+
return;
3136+
}
3137+
3138+
client.connect((err, client) => {
3139+
expect(err).to.not.exist;
3140+
3141+
let selectedServer;
3142+
const selectServerStub = sinon.stub(client.topology, 'selectServer').callsFake(function() {
3143+
const args = Array.prototype.slice.call(arguments);
3144+
const originalCallback = args.pop();
3145+
args.push((err, server) => {
3146+
selectedServer = server;
3147+
originalCallback(err, server);
3148+
});
3149+
3150+
return client.topology.selectServer.wrappedMethod.apply(this, args);
3151+
});
3152+
3153+
const collection = client.db().collection('test_read_preference');
3154+
collection.find().toArray(err => {
3155+
expect(err).to.not.exist;
3156+
expect(selectedServer.description.type).to.eql('RSSecondary');
3157+
3158+
client.close(err => {
3159+
selectServerStub.restore();
3160+
done(err);
3161+
});
3162+
});
3163+
});
3164+
}
3165+
});
31243166
});

0 commit comments

Comments
 (0)