Node.js MongoDB and Time-out Error
February 22, 2023•133 words
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