Dinesh Gowda
Dinesh Gowda

Reputation: 1144

is it possible to set read preference at mongoose query level

I have a mongo DB cluster with 1 primary and 2 secondaries. The replication lag is usually around 15 seconds. There are some critical sections of my code where we write and immediately read, which will end up in dirty reads. So I am exploring an option where I can pass read pref as an option at the query level.

mongoose.connect('mongodb://localhost/myapp');
var MyModel = mongoose.model('Test', new Schema({ name: String }));
MyModel.findOne({'name':'dinesh'}) // thinking of sending read pref here

When I call findOne, is there a way to pass read pref in the query itself or do I have to do it while connecting to mongo?

Upvotes: 1

Views: 1245

Answers (1)

Joe
Joe

Reputation: 28326

Yes, findOne accepts an options object that can include a read preference.

Model.findOne()

Parameters

[conditions] «Object» [projection] «Object|String|Array» optional fields to return, see Query.prototype.select() [options] «Object» optional see Query.prototype.setOptions() [callback] «Function» Returns:

«Query»

Upvotes: 2

Related Questions