Mongoose: Read on ReplicaSet

Viewed 16094

I have a mongodb replica set from which I want to read data from primary and secondary db.

I have used this command to connect to the db:

mongoose.connect('mongodb://user:password@54.230.1.1,user:password@54.230.1.2,user:password@54.230.1.3/PanPanDB?replicaSet=rs0&readPreference=nearest');

It doesn't work.. My application continues to read from the primary.. Any suggestion please?

6 Answers

This is the proper instantiation in Mongoose v5.9.5:

const opts = {
    readPreference: 'nearest',
}
mongoose.connect(MONGODB_CONNECTION, opts)

These are the different string values depending on the preference type you're looking for:

ReadPreference.PRIMARY = 'primary';
ReadPreference.PRIMARY_PREFERRED = 'primaryPreferred';
ReadPreference.SECONDARY = 'secondary';
ReadPreference.SECONDARY_PREFERRED = 'secondaryPreferred';
ReadPreference.NEAREST = 'nearest'
Related