mongo read from slave with primaryPreferred and mongoose - node.js

i've got a replica set on compose.io.
I've setted primaryPreferred on the config which is fine.
{ replset: {
rs_name: 'set-53453xxxxxxxxx',
strategy: 'ping',
read_secondary: true,
readPreference: 'primaryPreferred',
slaveOk: true,
safe: true,
socketOptions: { keepAlive: 1 }
}}
But i'd like to read on secondary for background process such as stats.
should i open 2 connections ? one for primary, and one for slave ?
that's what i did. But when connecting on the slave i get a not master and slaveOk=false when querying.
i know that i can rs.slaveOK() on the mongo client to allow query but i need it in my app connection
this is how i init my slave connection:
var slaveCon = mongoose.createConnection()
slaveCon.open('slaveURL', { slaveOk: true }, callback)
// this give me the notMaster error when querying
any ideas ?

Related

How to auto reconnect if mongo connection fails in node.js using mongoose?

I have mongodb up and running in a docker container. I stop the container and node returns a MongoError. I restart the container and node continues to throw the same MongoError.
I would like for it to reconnect when there was an issue.
const uri: string = this.config.db.uri;
const options = {
useNewUrlParser: true,
useCreateIndex: true,
autoIndex: true,
autoReconnect: true,
},
mongoose.connect(uri, options).then(
() => {
this.log.info("MongoDB Successfully Connected On: " + this.config.db.uri);
},
(err: any) => {
this.log.error("MongoDB Error:", err);
this.log.info("%s MongoDB connection error. Please make sure MongoDB is running.");
throw err;
},
);
How do i setup mongoose to try and auto connect when there is a connection failure to mongodb.
I found my answer, instead of checking error events and reconnecting like others have suggested. There are some options you can set that will handle auto-reconnect.
Here are the set of mongoose options i am now using.
const options = {
useNewUrlParser: true,
useCreateIndex: true,
autoIndex: true,
reconnectTries: Number.MAX_VALUE, // Never stop trying to reconnect
reconnectInterval: 500, // Reconnect every 500ms
bufferMaxEntries: 0,
connectTimeoutMS: 10000, // Give up initial connection after 10 seconds
socketTimeoutMS: 45000, // Close sockets after 45 seconds of inactivity
}
You can test it works by starting and stoping mongodb in a container and checking your node application.
For furuther information refer to this part of the documentation. https://mongoosejs.com/docs/connections.html#options

Mongoose Replicaset Connection Not Working

I am trying to connect to AWS MongoDB instances and its not even attempting to connect:
This is the connection URI:
mongodb://<usr>:<pwd>#host:port,host2:port2/db
And this is the code I am using to connect.
var mongoose = require('mongoose');
var dbOptions = { server: { socketOptions: { keepAlive: 300000, connectTimeoutMS: 30000 } },
replset: { socketOptions: { keepAlive: 300000, connectTimeoutMS : 30000 } } };
mongoose.connect(uri, dbOptions);
I also added logs inside events.. none of the events are firing. If I remove host2:port2 it works. So issue seems to be with the connection string. But connection string looks totally fine.. but still its not working.. Any idea why?

MongoClient.connect: Searching for a robust way to reconnect to a MongoDB host

I have a long running Node.js server task which connects to various MongoDB hosts with
// MongoClient options
// TODO: Unable to verify reconnect options
var clientConnectOptions = {
autoReconnect: true,
auto_reconnect: true,
server: {
sslKey: fs.readFileSync('X509key.pem'),
sslCert: fs.readFileSync('X509cert.pem'),
sslPass: null,
sslValidate: false,
checkServerIdentity: false
},
bufferMaxEntries: 0
}
MongoClient.connect('mongodb://server:port/test?ssl=prefer', clientConnectOptions, function cbDBConnect (err, db) { ... }
If the connection to the MongoDB host interrupts for a short time, my application reconnects as planned. But when the session disconnects for several minutes, the MongoClient does not reconnect any more.
I have looked at various reconnect options, but all attempts failed. How can I code a robust way to reconnect automatically?

mongoose readPreference in options object?

right now i am connecting to mongodb like this:
uri = 'mongodb://mongodomain1.com:1234,mongodomain2.com:1234/mydb?replicaSet=replicasetname&readPreference=secondaryPreferred';
opts = {
user: 'myuser',
pass: 'mypass',
server: {
auto_reconnect: true,
socketOptions: {
keepAlive: 120
}
},
replset: {
socketOptions: {
keepAlive: 120
}
}
};
mongoose.connect(uri, opts);
now i would like to bring the readPreference url parameter into the options object to be consitent and have all connection variables in the options.
i am struggling to find documentation on how to define the readPreference in the object.
same thing the replicaSet parameter in the url. is that equivalent to the rs_name
is there anything else i could/should improve in the way i am connecting to mongodb?

multiple connection to mongodb in node.js

In below code we can connect MongoDB
var options = {
db: { native_parser: true },
server: { poolSize: 5 },
replset: { rs_name: 'myReplicaSetName' },
user: 'myUserName',
pass: 'myPassword'
}
mongoose.connect(uri, options);
Here poolSize is 5. So that 5 parallel connection can be perform on request.
But I see if we try to create second connect node gives error that I'm trying to create connection which is not closed. So at the same time one connection can do perform for one application.
So what is meaning of poolSize is 5 and how it perform?
I need a solution and a way to increase pool size when my system is scale up.
Thanks in advanced.
Mongoose (or rather the mongodb driver it uses) will automatically manage the number of connections to the MongoDB server. You should call mongoose.connect() just once.
If you need a larger number of connections, all you have to do is increase the poolSize property. However, since you're using a replicate set, you should set replset.poolSize instead of server.poolSize:
var options = {
db: { native_parser: true },
replset: { rs_name: 'myReplicaSetName', poolSize : POOLSIZE },
user: 'myUserName',
pass: 'myPassword'
}

Resources