The nodejs mongodb driver disconnects the connection in standby mode and does not reconnect.
Background
The script below connects to mongodb and saves the database link in the global variable "db"
config = require("./config.js"); express = require("express"); mongodb = require("mongodb"); db = null; options = { auto_reconnect: true, db: { w: 1 } }; mongodb.MongoClient.connect(config.mongo, options, function(err, database) { if (err !== null) return console.log(err); db = database; console.log("successfully connected to mongodb"); db.on("close", (function() { return console.log("Connection to database closed automagically " + arguments); })); db.on("error", function(err) { return console.log("Db error " + err); }); app.listen(port); return console.log("listening for connections on " + port); });
Whenever I receive an insert request from a client, the following function is called:
insert = function(collectionName, object) { return db.collection(collectionName).insert(object, {w: 1}, (function(err) { return console.log("insert complete with err = " + err); })); };
Question
When the server receives an insert request after a long time, it fails or sometimes displays an error message unable to insert object (Error: failed to connect to [host:port])
Question
Is there a way to prevent this behavior? I tried to use the auto_reconnect option and write about problem 1, but none of them helped.
Thanks!
Furqan zafar
source share