Home > Enterprise >  Connecting to documentDB using mongodb 4.x node driver with port forwarding not working
Connecting to documentDB using mongodb 4.x node driver with port forwarding not working

Time:12-02

I have locally setup a port forwarding to the documentDB that is working successfully on the mongodb driver versions 3.x. When I update the mongodb package to 4.x I am getting an error of a timeout with the reason ReplicaSetNoPrimary.

The code is very simple:

const MongoClient = require('mongodb').MongoClient;


const client = new MongoClient('mongodb://xxxx:xxxx@localhost:27017');


client.connect(function(err) {
  if (err) {
    console.log(err);
    return;
  }
  
  const db = client.db('testdb');

  console.log("Connected successfully to server");

  client.close();
});

Has anyone been able to connect to the documentDB locally using port forwarding with the 4.x driver? Am I missing some sort of config options? (Keep in mind I have disabled all tls and everything to make it simpler to connect and as previously stated, successfully connect when using the mongodb 3.x packages)

CodePudding user response:

When connecting to a replica set, the driver:

  1. uses the host in the connection string as a seed to make an initial connection.
  2. runs the isMaster or hello command on that initial connection to get the full list of host:port replica set members and their current status
  3. drops the initial connections
  4. connects to each of the members discovered in step #2
  5. during operations, automatically monitors all of the members, sending operation to the primary even if a different node becomes primary

In your scenario, even though you are connecting to localhost, the initial connection returns the host:port pairs that are included in the replica set configuration.

The reason that this just became a problem is the MongoDB driver specifications changed to use unified topology by default.

Unified topology permits the driver to automatically detect if it is connecting to a standalone instance, replica set, or sharded cluster, which simplifies the connection process and reduces the administrative overhead required when changing how the database is deployed.

Since your connection is failing, I assume the hostname:port pairs listed in the replica set config are either not resolvable or not reachable from the test host.

To resolve this situation either:

  • make it so this machine can resolve the hostnames via DNS or hosts file, and permit the connections to those ports through any firewalls
  • use the directConnection=true connection option to disable topology discovery
  • Related