node.jsmongodbnode-mongodb-native

mongodb node driver connect() ignores connectTimeoutMS (and socketTimeoutMS) settings


I'm using mongodb node driver version 4.7.0 (latest at the moment of writing this). I have the following fragment of code to connect to DB:

var url = "<my mongodb:// URI>";
var client = require('mongodb').MongoClient;
client.connect(
    url,
    {
        connectTimeoutMS: 2000
    },
    <callback function>);

So it should timeout if DB doesn't exist after 2 seconds (2000 ms). However, the timeouts takes place at 30s (30000 ms), which I guess is the default for the setting. In other words, it seems that connectTimeoutMS is being ignored.

I have also tried with socketTimeoutMS: 2000 and combining both connectTimeoutMS: 2000 and socketTimeoutMS: 2000 and the result is the same.

Maybe I'm doing something wrong?


Solution

  • This is to do with how unified topology works.

    You are always considered "connected" by the driver and then under the hood it auto reconnects for you, but if you want to timeout on the initial server selection (e.g. to detect if mongo is down initially), you can do this with serverSelectionTimeoutMS

    I suspect the other timeout options are honored properly, just deeper down the stack so you don't notice it.