Search code examples
node.jsmongodbreplicaset

Does the MongoDB connection string need the authentication details for each server in ReplicaSet?


We've discovered that our secondary is not authenticating properly after having the primary fail over to it. We have 2 MongoDB servers (v3.4) both properly setup in a replicaset:

mongo1:27017
mongo2:27017

And our connection string (for Node.js's MongoDB driver v2.2.19), is like this:

mongodb://username:password@mongo1,mongo2/db?replicaSet=rs0

Now, our primary failed and the secondary, mongo2 was elected primary. However, DB calls failed with 'not authorized' errors. So I took another look at the MongoDB docs:

mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]

It looks ambiguous, could the username:password be needed for each host? But that's weird because they are all replicated so the users should be the same, right?

I even tried it, using this connection string in the application:

mongodb://username:password@mongo1,username:password@mongo2/db?replicaSet=rs0

But that fails with: Error: Username with password containing an unescaped colon

The username and passwords are alphanumeric, so there seems to be a parsing problem with that style URI. But with the original, it's not authenticated properly. So these problems seem at odds with each other. I have verified in standalone mode that the user exists on both servers, and has the proper permissions. So I'm not sure where the problem lies. I found another very similar question with a different driver, but no answers :(


Solution

  • Well, I could never figure this out but updating the Node.js driver (v2.2.19 -> v2.2.33) seems to have fixed it. I didn't see anything relevant in the changelog and I'm not interested enough to compare diffs. C'est la vie de programming.