Skip to content

Commit

Permalink
fix: sets primary read preference for writes
Browse files Browse the repository at this point in the history
Uses a primary read preference for write / DDL operations, needed for server selection.

NODE-2784
  • Loading branch information
Thomas Reggi committed Sep 21, 2020
1 parent 4e03dfa commit ddcd03d
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/operations/command_v2.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ class CommandOperationV2 extends OperationBase {

this.ns = parent.s.namespace.withCollection('$cmd');
const propertyProvider = this.hasAspect(Aspect.NO_INHERIT_OPTIONS) ? undefined : parent;
this.readPreference = ReadPreference.resolve(propertyProvider, this.options);
this.readPreference = this.hasAspect(Aspect.WRITE_OPERATION)
? ReadPreference.primary
: ReadPreference.resolve(propertyProvider, this.options);
this.readConcern = resolveReadConcern(propertyProvider, this.options);
this.writeConcern = resolveWriteConcern(propertyProvider, this.options);
this.explain = false;
Expand Down
40 changes: 40 additions & 0 deletions test/functional/collection.test.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
'use strict';
const Topology = require('../../lib/core/sdam/topology').Topology;
const setupDatabase = require('./shared').setupDatabase;
const chai = require('chai');
const expect = chai.expect;
const sinonChai = require('sinon-chai');
const mock = require('mongodb-mock-server');
const ReadPreference = require('../../lib/core/topologies/read_preference');
chai.use(sinonChai);

describe('Collection', function() {
Expand Down Expand Up @@ -1307,4 +1309,42 @@ describe('Collection', function() {
});
}
});

context('DDL methods with serverSelection readPreference primary', () => {
const collectionMethodSet = {
createIndex: [{ quote: 'text' }]
};

Object.keys(collectionMethodSet).forEach(operation => {
it(`should ${operation} with serverSelection readPreference primary`, {
metadata: {
requires: { topology: 'replicaset' }
},
test: function(done) {
const opArgs = collectionMethodSet[operation];
const configuration = this.configuration;
const client = configuration.newClient(configuration.writeConcernMax(), {
useUnifiedTopology: true,
readPreference: 'primaryPreferred'
});
client.connect((err, client) => {
expect(err).to.not.exist;
const db = client.db(configuration.db);
const collection = db.collection('db-two');
const TopologySpy = this.sinon.spy(Topology.prototype, 'selectServer');
const callback = err => {
expect(err).to.not.exist;
expect(TopologySpy.called).to.equal(true);
expect(TopologySpy)
.nested.property('args[0][0].readPreference.mode')
.to.equal(ReadPreference.PRIMARY);
client.close(done);
};
opArgs.push(callback);
collection[operation].apply(collection, opArgs);
});
}
});
});
});
});

0 comments on commit ddcd03d

Please sign in to comment.