Note: The Listed platform will permanently shut down December 31, 2026. Your data published on Listed will still be available in your personal Standard Notes account. Learn more

Node.js MongoDB and Time-out Error

MongoDB connection timeout error is usually by firewall set on server but there's a abnormal case as described below.

Case 1: No Error

const log           = console.log;
const {MongoClient} = require("mongodb");
var   Client        = new MongoClient("some-url");

(async function(){
    await Client.connect();
    log("Okay");
})();

Case 2: Time-out Error

const log           = console.log;
const {MongoClient} = require("mongodb");
var   Client        = new MongoClient("some-url");

Client.connect().then(()=>{
    log("Okay");
}).
catch(Err=>{
    log(Err);
});

// Node.js is single-threaded
// do some intensive task here longer than MongoClient.connect timeout
// After the intensive task, thread control is passed to the 
// MongoClient instance, and it calculates passed time, which is long
// and time-out error will appear.

Solution

  • Use await
  • Or set large connectTimeoutMS in MongoDB connection URL, very large, eg. 3600000ms = 1hr

You'll only receive email when they publish something new.

More from Arno
All posts