Reputation: 147
I try to set read preference to read data from secodary but It's not working when using transaction on some API
e.g I'am using mongoose with node js
const mongoose = require("mongoose");
const connect = () => {
mongoose
.connect(mongoURI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
readPreference:"secondaryPreferred",
keepAlive:1,
replicaSet: "dpx_rs",
writeConcern:"majority"
})
.then(() => {
console.log("MongoDB Connected");
})
.catch((err) => console.log(err));
};
Error response
MongoError: Read preference in a transaction must be primary,
not: secondaryPreferred
Upvotes: 3
Views: 5550
Reputation: 1441
When you perform the connection setup on Mongoose, change the readPreference property to primary. Currently as the error message indicate you have set secondaryPreferred.
Your code should then be something like that
const mongoose = require("mongoose");
const connect = () => {
mongoose
.connect(mongoURI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
readPreference:"primary",
keepAlive:1,
replicaSet: "dpx_rs",
writeConcern:"majority"
})
.then(() => {
console.log("MongoDB Connected");
})
.catch((err) => console.log(err));
Of course, this is if you want that setting to be global and by default on your connection pool. As you mentioned, you can override these settings per session for specific queries if you need.
Upvotes: 1
Reputation: 147
I have two condition inside a function two of them use Transaction, I found something when start transaction I set read preference into session option it's working on frist condition and second one don't know readPreference key option
const opts ={ session, readPreference:"primary" };
So, I try to add readPreference only inside first condition it works
opts.readPreference = "primary"
But if i do this I have to find another function that's not working how can i set it globally
Upvotes: 1