0

I am using mongoose to connect mongo(v3.04) replica set, and I want to spread all my requests to all nodes in set. However, after doing like the following, my secondary never got hit, my connection string and options like the following:

let connectionString = 'mongodb://ip1:27017/db, ip2:27017/db';
mongoose.connect(connectionString, {
    server: {
        socketOptions:  {keepAlive: 1},
        readPreference: "nearest",
        strategy: "ping"
    },
    replset: {
        rs_name: 'ReplicaSet',
        socketOptions:  {keepAlive: 1},
        strategy: 'ping',
        readPreference: 'nearest',
        poolSize: 10
    }
});

It looks like the mongoose totally ignore the readPreference settings I passed. I already tried many ways mentioned here, but so far no luck. Anyone could give me a hint?

Ron
  • 6,037
  • 4
  • 33
  • 52
  • *>> but my secondary never got hit* << what do you mean by this? What exactly do you expect to see that is not happening? – Dmytro Shevchenko Nov 11 '15 at 09:07
  • I want to spread queries to all nodes in replica set. Or I want to control read preference through mongoose options. – Ron Nov 11 '15 at 09:29
  • Requests? Don't you mean reads? Only reads can be gotten from non-primaries, is that your problem? – Sammaye Nov 11 '15 at 09:35
  • Also have you checked that your secondary is not only nearest but also responds fastest? – Sammaye Nov 11 '15 at 09:36
  • Yes, requests in my post means reads. – Ron Nov 11 '15 at 09:36
  • @Sammaye, I tried to restart my primary, and it become secondary after startup. After that, the other node (which was secondary and just become primary) got hit. – Ron Nov 11 '15 at 09:38
  • Hmm, the docs on this are so bad, I have some conflicting info on how to set read preference: http://stackoverflow.com/questions/20714340/mongoose-read-on-replicaset – Sammaye Nov 11 '15 at 09:41

1 Answers1

6

readPreference: 'nearest' means that clients will ping all replica-set members on connect and address all future reads to the one which responds the fastest. MongoDB clients will usually not switch between primary and secondary randomly.

When you want them to read from the secondary, use readPreference: 'secondaryPreferred'.

Philipp
  • 67,764
  • 9
  • 118
  • 153
  • Because by default it was primary, and after I set to nearest, it still work as before. – Ron Nov 11 '15 at 09:31
  • Do note the docs on this: "Operations read from member of the replica set with the least network latency, irrespective of the member’s type." https://docs.mongodb.org/manual/reference/read-preference/#nearest – Sammaye Nov 11 '15 at 09:38