Use Mongoose insert about 70 objects with MongoError:read ECONNRESET - node.js

In my scenario, node need read a array of img files in a directory, and store binaries to MongoDB. This function is to test the ability of store file to MongoDB. The img file size range 5kb to 3mb.
Part 1. connect mongdb
I use the options parameter to set the socket's keepAlive, I want to the socket keep long.
var options = {
server: {
socketOptions: {
keepAlive: 1,
connectTimeoutMS: 30000
}
},
replset: {
socketOptions: {
keepAlive: 1,
connectTimeoutMS : 30000
}
}
};
mongoose.connect(mongooseURI, options);
Part 2. insert operation
fs can read the files successfully, but the number of files may cause a error, i will write lately. I use the collection.insert to store a array of data.
Img.collection.insert(fileArr, function(err, docs){
if(err){
console.info('\033[31mError: Failed to save docs with error: ', err, '\033[39m');
process.emit('DB_OPS_DONE', err.message);
}else{
console.info('%d images were successfully stored.', docs.length);
console.log('benchmark took %d nanoseconds', diff[0] * 1e9 + diff[1]);
process.emit('DB_OPS_DONE', 'Successful insert docs');
}
});
Part 3. close connection
This make the node app stop normally whether the error come up.
process.on('DB_OPS_DONE', function(msg) {
mongoose.connection.close(function () {
console.log('Mongoose disconnected on app termination with ', msg);
process.exit(0);
});
});
I get a error if the number of files become large. Number test out about 40.That means if the number of files < 40, the node can finish successfully.
The error is MongoError: server localhost:27017 received an error {"name":"MongoError","message":"read ECONNRESET"}
environment:
os: win7
nodejs: 0.10.31
mongodb: 2.7
mongoose: 4.0.5

Related

Mongodb useUnifiedTopology automatically create a new connection [duplicate]

I am having a kind of strange problem when I trying to establish a single mongodb connection to a db with the mongodb nodejs native driver in the version 3.6.0.
My idea is to have just one connection opened through all the client session and reuse it in the different routes I have in my express server, when I hit it the first time the getDatabase function it creates two connections and after that one of it closes and one stands idle, but when I use a route, the second get opened again (it is like one connection just stays there and do nothing).
I just want to have one connection opened in my pool.
If you see the commented code i was testing with those options but none of them worked for me.
Pd: when I set the socketTimeoutMS to 5000ms just one connection is created but it auto-closes and reopen each 5000ms, which is weird (it reopen itself even when I don't use the connection).
All of this problem happen when I set the useUnifiedTopology to true (I can't set it to false because is deprecated and the other topologies will be removed in the next version of mdb ndjs driver)
Here is an image with the strange behaviour
The code is:
import { MongoClient, Db } from 'mongodb';
import { DB_URI } from '../config/config';
// This mod works as DataBase Singleton
let db: Db;
export const getDataBase = async (id: string) => {
try {
if (db) {
console.log('ALREADY CREATED');
return db;
} else {
console.log('CREATING');
let client: MongoClient = await MongoClient.connect(`${DB_URI}DB_${id}`, {
useUnifiedTopology: true,
/* minPoolSize: 1,
maxPoolSize: 1,
socketTimeoutMS: 180000,
keepAlive: true,
maxIdleTimeMS:10000
useNewUrlParser: true,
keepAlive: true,
w: 'majority',
wtimeout: 5000,
serverSelectionTimeoutMS: 5000,
connectTimeoutMS: 8000,
appname: 'myApp',
*/
});
db = client.db();
return db;
}
} catch (error) {
console.log('DB Connection error', error);
}
};
The driver internally creates one connection per known server for monitoring purposes. This connection is not used for application operations.
Hence, it is expected that you would get two connections established.

How to fix nodejs connect to mongo "MongoError: topology was destroyed" [duplicate]

I have a REST service built in node.js with Restify and Mongoose and a mongoDB with a collection with about 30.000 regular sized documents.
I have my node service running through pmx and pm2.
Yesterday, suddenly, node started crapping out errors with the message "MongoError: Topology was destroyed", nothing more.
I have no idea what is meant by this and what could have possibly triggered this. there is also not much to be found when google-searching this. So I thought I'd ask here.
After restarting the node service today, the errors stopped coming in.
I also have one of these running in production and it scares me that this could happen at any given time to a pretty crucial part of the setup running there...
I'm using the following versions of the mentioned packages:
mongoose: 4.0.3
restify: 3.0.3
node: 0.10.25
It seems to mean your node server's connection to your MongoDB instance was interrupted while it was trying to write to it.
Take a look at the Mongo source code that generates that error
Mongos.prototype.insert = function(ns, ops, options, callback) {
if(typeof options == 'function') callback = options, options = {};
if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed')));
// Topology is not connected, save the call in the provided store to be
// Executed at some point when the handler deems it's reconnected
if(!this.isConnected() && this.s.disconnectHandler != null) {
callback = bindToCurrentDomain(callback);
return this.s.disconnectHandler.add('insert', ns, ops, options, callback);
}
executeWriteOperation(this.s, 'insert', ns, ops, options, callback);
}
This does not appear to be related to the Sails issue cited in the comments, as no upgrades were installed to precipitate the crash or the "fix"
I know that Jason's answer was accepted, but I had the same problem with Mongoose and found that the service hosting my database recommended to apply the following settings in order to keep Mongodb's connection alive in production:
var options = {
server: { socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 } },
replset: { socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 } }
};
mongoose.connect(secrets.db, options);
I hope that this reply may help other people having "Topology was destroyed" errors.
This error is due to mongo driver dropping the connection for any reason (server was down for example).
By default mongoose will try to reconnect for 30 seconds then stop retrying and throw errors forever until restarted.
You can change this by editing these 2 fields in the connection options
mongoose.connect(uri,
{ server: {
// sets how many times to try reconnecting
reconnectTries: Number.MAX_VALUE,
// sets the delay between every retry (milliseconds)
reconnectInterval: 1000
}
}
);
connection options documentation
In my case, this error was caused by a db.close(); out of a 'await' section inside of 'async'
MongoClient.connect(url, {poolSize: 10, reconnectTries: Number.MAX_VALUE, reconnectInterval: 1000}, function(err, db) {
// Validate the connection to Mongo
assert.equal(null, err);
// Query the SQL table
querySQL()
.then(function (result) {
console.log('Print results SQL');
console.log(result);
if(result.length > 0){
processArray(db, result)
.then(function (result) {
console.log('Res');
console.log(result);
})
.catch(function (err) {
console.log('Err');
console.log(err);
})
} else {
console.log('Nothing to show in MySQL');
}
})
.catch(function (err) {
console.log(err);
});
db.close(); // <--------------------------------THIS LINE
});
Just a minor addition to Gaafar's answer, it gave me a deprecation warning. Instead of on the server object, like this:
MongoClient.connect(MONGO_URL, {
server: {
reconnectTries: Number.MAX_VALUE,
reconnectInterval: 1000
}
});
It can go on the top level object. Basically, just take it out of the server object and put it in the options object like this:
MongoClient.connect(MONGO_URL, {
reconnectTries: Number.MAX_VALUE,
reconnectInterval: 1000
});
"Topology was destroyed" might be caused by mongoose disconnecting before mongo document indexes are created, per this comment
In order to make sure all models have their indexes built before disconnecting, you can:
await Promise.all(mongoose.modelNames().map(model => mongoose.model(model).ensureIndexes()));
await mongoose.disconnect();
I met this in kubernetes/minikube + nodejs + mongoose environment.
The problem was that DNS service was up with a kind of latency. Checking DNS is ready solved my problem.
const dns = require('dns');
var dnsTimer = setInterval(() => {
dns.lookup('mongo-0.mongo', (err, address, family) => {
if (err) {
console.log('DNS LOOKUP ERR', err.code ? err.code : err);
} else {
console.log('DNS LOOKUP: %j family: IPv%s', address, family);
clearTimeout(dnsTimer);
mongoose.connect(mongoURL, db_options);
}
});
}, 3000);
var db = mongoose.connection;
var db_options = {
autoReconnect:true,
poolSize: 20,
socketTimeoutMS: 480000,
keepAlive: 300000,
keepAliveInitialDelay : 300000,
connectTimeoutMS: 30000,
reconnectTries: Number.MAX_VALUE,
reconnectInterval: 1000,
useNewUrlParser: true
};
(the numbers in db_options are arbitrary found on stackoverflow and similar like sites)
I alse had the same error. Finally, I found that I have some error on my code. I use load balance for two nodejs server, but I just update the code of one server.
I change my mongod server from standalone to replication, but I forget to do the corresponding update for the connection string, so I met this error.
standalone connection string:
mongodb://server-1:27017/mydb
replication connection string:
mongodb://server-1:27017,server-2:27017,server-3:27017/mydb?replicaSet=myReplSet
details here:[mongo doc for connection string]
Sebastian comment on Adrien's answer needs more attention it helped me but it being a comment might be ignore sometime so here's a solution:
var options = { useMongoClient: true, keepAlive: 1, connectTimeoutMS: 30000, reconnectTries: 30, reconnectInterval: 5000 }
mongoose.connect(config.mongoConnectionString, options, (err) => {
if(err) {
console.error("Error while connecting", err);
}
});
Here what I did, It works fine. Issue was gone after adding below options.
const dbUrl = "mongodb://localhost:27017/sampledb";
const options = { useMongoClient: true, keepAlive: 1, connectTimeoutMS: 30000, reconnectTries: 30, reconnectInterval: 5000, useNewUrlParser: true }
mongoose.connect(dbUrl,options, function(
error
) {
if (error) {
console.log("mongoerror", error);
} else {
console.log("connected");
}
});
You need to restart mongo to solve the topology error, then just change some options of mongoose or mongoclient to overcome this problem:
var mongoOptions = {
useMongoClient: true,
keepAlive: 1,
connectTimeoutMS: 30000,
reconnectTries: Number.MAX_VALUE,
reconnectInterval: 5000,
useNewUrlParser: true
}
mongoose.connect(mongoDevString,mongoOptions);
I got this error, while I was creating a new database on my MongoDb Compass Community. The issue was with my Mongod, it was not running. So as a fix, I had to run the Mongod command as preceding.
C:\Program Files\MongoDB\Server\3.6\bin>mongod
I was able to create a database after running that command.
Hope it helps.
I was struggling with this for some time - As you can see from other answers, the issue can be very different.
The easiest way to find out whats causing is this is to turn on loggerLevel: 'info' in the options
In my case, this error was caused by an identical server instance already running background.
The weird thing is when I started my server without notice there's one running already, the console didn't show anything like 'something is using port xxx'. I could even upload something to the server. So, it took me quite long to locate this problem.
What's more, after closing all the applications I can imagine, I still could not find the process which is using this port in my Mac's activity monitor. I have to use lsof to trace. The culprit was not surprising - it's a node process. However, with the PID shown in the terminal, I found the port number in the monitor is different from the one used by my server.
All in all, kill all the node processes may solve this problem directly.
Using mongoose here, but you could do a similar check without it
export async function clearDatabase() {
if (mongoose.connection.readyState === mongoose.connection.states.disconnected) {
return Promise.resolve()
}
return mongoose.connection.db.dropDatabase()
}
My use case was just tests throwing errors, so if we've disconnected, I don't run operations.
I got this problem recently. Here what I do:
Restart MongoDb: sudo service mongod restart
Restart My NodeJS APP. I use pm2 to handle this pm2 restart [your-app-id]. To get ID use pm2 list
var mongoOptions = {
useNewUrlParser: true,
useUnifiedTopology: true,
}
mongoose.connect(mongoDevString,mongoOptions);
I solved this issue by:
ensuring mongo is running
restarting my server

When mongodb server is down how to catch the error while running mongoose query

I am using mongoose for connecting node.js with mongoDB, now i wrote below query
var trans = new transmodel({method: method, trans_id: r});
trans.save(function(err) {
if (err) {
console.error("Razor_pay_webhook Error 4 err: " + err);
res.write('statusCode: 200');
res.end();
} else {
res.write('statusCode: 400');
res.end();
}
});
I thought when my mongodb cluster will be down then i will get 'err' while executing above mongoose query, but when i ran above query while my mongo cluster was down nothing happened(No err was called). Can anyone please tell me how can i catch the error if my mongodb server is down inside my query. Also for reconnecting again with my cluster i have set below parameters but my node server is not trying to reconnect again with my mongodb server i don't know what's going wrong.
var mongoose = require('mongoose');
var config = require('./config/database.js');
var DB_URL = config.db.url;
mongoose.connection.on("connected", function(ref) {
console.log("Connected to " + " DB!");
});
mongoose.connection.on("error", function(err) {
console.error('Failed to connect to DB ' + ' on startup ', err);
if (err) {
return next(err);
}
});
mongoose.connection.on('disconnected', function(err) {
console.log('Mongoose default connection to DB :' + ' disconnected');
if (err) {
return next(err);
}
});
var gracefulExit = function() {
mongoose.connection.close(function () {
console.log('Mongoose default connection with DB :' + ' is disconnected through app termination');
process.exit(0);
});
}
process.on('SIGINT', gracefulExit).on('SIGTERM', gracefulExit);
exports.con_close = function () {
console.log('Mongoose connection disconnected');
mongoose.connection.close();
}
var options = {
server: {
socketOptions: {
keepAlive: 1000,
connectTimeoutMS: 30000
}
},
replset: {
rs_name: 'replicaset',
auto_reconnect:true,
socketOptions: {
keepAlive: 1000, // doubt about it
connectTimeoutMS: 30000
}
},
user: 'root',
pass: 'G3saGT2Y',
auth: {
authdb: 'admin'
}
}
mongoose.connect(DB_URL, options, function(err) {
console.log('ho rha hai');
if (err) {
console.log('error connection to mongo server!');
console.log(err);
}
});
You are using mongoose, it emits events (the EventEmitter pattern) when the database is down and when the database is reconnecting and up again.
from mongoose code found here we can see that the library db connection - connection.js
has the following events that are emitted:
* #param {Mongoose} base a mongoose instance
* #inherits NodeJS EventEmitter
http://nodejs.org/api/events.html#events_class_events_eventemitter
* #event connecting: Emitted when connection.{open,openSet}() is executed on this connection.
#event connected: Emitted when this connection successfully connects to the db. May be emitted multiple times in reconnected scenarios.
#event open: Emitted after we connected and onOpen is executed on all of this connections models.
#event disconnecting: Emitted when connection.close() was executed.
#event disconnected: Emitted after getting disconnected from the db.
#event close: Emitted after we disconnected and onClose executed on all of this connections models.
#event reconnected: Emitted after we connected and subsequently disconnected, followed by successfully another successfull connection.
#event error: Emitted when an error occurs on this connection.
#event fullsetup: Emitted in a replica-set scenario, when primary and at
least one seconaries specified in the connection string are connected.
#event all: Emitted in a replica-set scenario, when all nodes specified in the connection string are connected.
When the database is down you will receive two events:
1. disconnected
2. error (the error that driver encountered)
When the database is up again you will receive the reconnect event.
So you don't need to try catch the error rather you should listen to these events.
More helpful information about connection failures and reconnecting can be found here.
This article explain how to use and configure the autoReconnect and the bufferMaxEntries according to your settings.

mongoError: Topology was destroyed

I have a REST service built in node.js with Restify and Mongoose and a mongoDB with a collection with about 30.000 regular sized documents.
I have my node service running through pmx and pm2.
Yesterday, suddenly, node started crapping out errors with the message "MongoError: Topology was destroyed", nothing more.
I have no idea what is meant by this and what could have possibly triggered this. there is also not much to be found when google-searching this. So I thought I'd ask here.
After restarting the node service today, the errors stopped coming in.
I also have one of these running in production and it scares me that this could happen at any given time to a pretty crucial part of the setup running there...
I'm using the following versions of the mentioned packages:
mongoose: 4.0.3
restify: 3.0.3
node: 0.10.25
It seems to mean your node server's connection to your MongoDB instance was interrupted while it was trying to write to it.
Take a look at the Mongo source code that generates that error
Mongos.prototype.insert = function(ns, ops, options, callback) {
if(typeof options == 'function') callback = options, options = {};
if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed')));
// Topology is not connected, save the call in the provided store to be
// Executed at some point when the handler deems it's reconnected
if(!this.isConnected() && this.s.disconnectHandler != null) {
callback = bindToCurrentDomain(callback);
return this.s.disconnectHandler.add('insert', ns, ops, options, callback);
}
executeWriteOperation(this.s, 'insert', ns, ops, options, callback);
}
This does not appear to be related to the Sails issue cited in the comments, as no upgrades were installed to precipitate the crash or the "fix"
I know that Jason's answer was accepted, but I had the same problem with Mongoose and found that the service hosting my database recommended to apply the following settings in order to keep Mongodb's connection alive in production:
var options = {
server: { socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 } },
replset: { socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 } }
};
mongoose.connect(secrets.db, options);
I hope that this reply may help other people having "Topology was destroyed" errors.
This error is due to mongo driver dropping the connection for any reason (server was down for example).
By default mongoose will try to reconnect for 30 seconds then stop retrying and throw errors forever until restarted.
You can change this by editing these 2 fields in the connection options
mongoose.connect(uri,
{ server: {
// sets how many times to try reconnecting
reconnectTries: Number.MAX_VALUE,
// sets the delay between every retry (milliseconds)
reconnectInterval: 1000
}
}
);
connection options documentation
In my case, this error was caused by a db.close(); out of a 'await' section inside of 'async'
MongoClient.connect(url, {poolSize: 10, reconnectTries: Number.MAX_VALUE, reconnectInterval: 1000}, function(err, db) {
// Validate the connection to Mongo
assert.equal(null, err);
// Query the SQL table
querySQL()
.then(function (result) {
console.log('Print results SQL');
console.log(result);
if(result.length > 0){
processArray(db, result)
.then(function (result) {
console.log('Res');
console.log(result);
})
.catch(function (err) {
console.log('Err');
console.log(err);
})
} else {
console.log('Nothing to show in MySQL');
}
})
.catch(function (err) {
console.log(err);
});
db.close(); // <--------------------------------THIS LINE
});
Just a minor addition to Gaafar's answer, it gave me a deprecation warning. Instead of on the server object, like this:
MongoClient.connect(MONGO_URL, {
server: {
reconnectTries: Number.MAX_VALUE,
reconnectInterval: 1000
}
});
It can go on the top level object. Basically, just take it out of the server object and put it in the options object like this:
MongoClient.connect(MONGO_URL, {
reconnectTries: Number.MAX_VALUE,
reconnectInterval: 1000
});
"Topology was destroyed" might be caused by mongoose disconnecting before mongo document indexes are created, per this comment
In order to make sure all models have their indexes built before disconnecting, you can:
await Promise.all(mongoose.modelNames().map(model => mongoose.model(model).ensureIndexes()));
await mongoose.disconnect();
I met this in kubernetes/minikube + nodejs + mongoose environment.
The problem was that DNS service was up with a kind of latency. Checking DNS is ready solved my problem.
const dns = require('dns');
var dnsTimer = setInterval(() => {
dns.lookup('mongo-0.mongo', (err, address, family) => {
if (err) {
console.log('DNS LOOKUP ERR', err.code ? err.code : err);
} else {
console.log('DNS LOOKUP: %j family: IPv%s', address, family);
clearTimeout(dnsTimer);
mongoose.connect(mongoURL, db_options);
}
});
}, 3000);
var db = mongoose.connection;
var db_options = {
autoReconnect:true,
poolSize: 20,
socketTimeoutMS: 480000,
keepAlive: 300000,
keepAliveInitialDelay : 300000,
connectTimeoutMS: 30000,
reconnectTries: Number.MAX_VALUE,
reconnectInterval: 1000,
useNewUrlParser: true
};
(the numbers in db_options are arbitrary found on stackoverflow and similar like sites)
I alse had the same error. Finally, I found that I have some error on my code. I use load balance for two nodejs server, but I just update the code of one server.
I change my mongod server from standalone to replication, but I forget to do the corresponding update for the connection string, so I met this error.
standalone connection string:
mongodb://server-1:27017/mydb
replication connection string:
mongodb://server-1:27017,server-2:27017,server-3:27017/mydb?replicaSet=myReplSet
details here:[mongo doc for connection string]
Sebastian comment on Adrien's answer needs more attention it helped me but it being a comment might be ignore sometime so here's a solution:
var options = { useMongoClient: true, keepAlive: 1, connectTimeoutMS: 30000, reconnectTries: 30, reconnectInterval: 5000 }
mongoose.connect(config.mongoConnectionString, options, (err) => {
if(err) {
console.error("Error while connecting", err);
}
});
Here what I did, It works fine. Issue was gone after adding below options.
const dbUrl = "mongodb://localhost:27017/sampledb";
const options = { useMongoClient: true, keepAlive: 1, connectTimeoutMS: 30000, reconnectTries: 30, reconnectInterval: 5000, useNewUrlParser: true }
mongoose.connect(dbUrl,options, function(
error
) {
if (error) {
console.log("mongoerror", error);
} else {
console.log("connected");
}
});
You need to restart mongo to solve the topology error, then just change some options of mongoose or mongoclient to overcome this problem:
var mongoOptions = {
useMongoClient: true,
keepAlive: 1,
connectTimeoutMS: 30000,
reconnectTries: Number.MAX_VALUE,
reconnectInterval: 5000,
useNewUrlParser: true
}
mongoose.connect(mongoDevString,mongoOptions);
I got this error, while I was creating a new database on my MongoDb Compass Community. The issue was with my Mongod, it was not running. So as a fix, I had to run the Mongod command as preceding.
C:\Program Files\MongoDB\Server\3.6\bin>mongod
I was able to create a database after running that command.
Hope it helps.
I was struggling with this for some time - As you can see from other answers, the issue can be very different.
The easiest way to find out whats causing is this is to turn on loggerLevel: 'info' in the options
In my case, this error was caused by an identical server instance already running background.
The weird thing is when I started my server without notice there's one running already, the console didn't show anything like 'something is using port xxx'. I could even upload something to the server. So, it took me quite long to locate this problem.
What's more, after closing all the applications I can imagine, I still could not find the process which is using this port in my Mac's activity monitor. I have to use lsof to trace. The culprit was not surprising - it's a node process. However, with the PID shown in the terminal, I found the port number in the monitor is different from the one used by my server.
All in all, kill all the node processes may solve this problem directly.
Using mongoose here, but you could do a similar check without it
export async function clearDatabase() {
if (mongoose.connection.readyState === mongoose.connection.states.disconnected) {
return Promise.resolve()
}
return mongoose.connection.db.dropDatabase()
}
My use case was just tests throwing errors, so if we've disconnected, I don't run operations.
I got this problem recently. Here what I do:
Restart MongoDb: sudo service mongod restart
Restart My NodeJS APP. I use pm2 to handle this pm2 restart [your-app-id]. To get ID use pm2 list
var mongoOptions = {
useNewUrlParser: true,
useUnifiedTopology: true,
}
mongoose.connect(mongoDevString,mongoOptions);
I solved this issue by:
ensuring mongo is running
restarting my server

mongodb db.open() returns replicaset error but no error in mongodb log files

NodeJS version: v0.10.29
Mongo version: 2.6.3
NodeJS mongodb module: 1.4.5
We are getting the following error in the callback to db.open
"Error: No valid replicaset instance servers found"
The mongodb seems to be working fine and there is no error in the mongodb logs. Restarting the nodejs server solves the problem.
From https://github.com/HabitRPG/habitrpg/issues/2725:
One of the odd things about the Node driver is that the default
timeout for replica set connections is only 1 second, so make sure
you're setting it to something more like 30s like in this example:
{
options: {
replset: { socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 } },
server: { socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 } }
}
}
I think they meant these as options for use with MongoClient().
I have seen this error when starting both a MongoDB cluster and Node.js at the same time.
As MongoDB replica sets require to elect a primary and do other hand shaking activities when they are started this can introduce a delay in the MongoDB instances being available to connect to. Making the issue you describe more likely to occur.
Increasing the timeout values on the connection, as rakslice's answer details, can prevent this.
It is worth referring to the official MongoDB documentation for connection timeout settings and explanation:
http://docs.mongodb.org/manual/reference/connection-string/#connection-options
To add rakslice's answer here is a full example of how you might connect to a replset with connection timeout values set:
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://localhost:27017,localhost:27017,localhost:27017/test",
{
replset: {
socketOptions: {
connectTimeoutMS: 30000
}
},
server: {
socketOptions: {
connectTimeoutMS: 500
}
}
},
function(err, db) {
if (err) throw err;
db.collection("things").find({}).toArray(function(err, docs) {
if (err) throw err;
console.log(docs);
db.close();
});
}
);
A good article that goes over some of the implications & decisions of setting a particular timeout value(s):
http://blog.mongolab.com/2013/10/do-you-want-a-timeout/

Resources