Skip to content

Instantly share code, notes, and snippets.

@geronime
Created July 8, 2016 14:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save geronime/a0362e6d02af74c88e927abaef286b9e to your computer and use it in GitHub Desktop.
Save geronime/a0362e6d02af74c88e927abaef286b9e to your computer and use it in GitHub Desktop.
'use strict';
const connUri = 'mongodb://localhost:37017,localhost:37018,localhost:37019/test';
const connOpts = {
db: {
bufferMaxEntries: 0
},
server: {
autoReconnect: true,
socketOptions: {
connectTimeoutMS: 1000 // for intial discovery of what is behind the connection string! all of the connection has to succeed so that the driver recognizes that the connection string isn't a mix of different topologies
}
},
mongos: {
poolSize: 1,
socketOptions: {
connectTimeoutMS: 1000
}
}
};
const queryTimeout = 1000;
const queryBackoff = 1000;
const MongoClient = require('mongodb').MongoClient;
const Logger = require('mongodb').Logger;
Logger.setLevel('debug'); // _
function startQuerying(db) {
let now = Date.now();
let timeout = setTimeout(function () {
console.log(new Date().toISOString(), 'Query timed out, ms:', Date.now() - now);
setTimeout(startQuerying, queryBackoff, db);
}, queryTimeout);
db.collection('test').findOne({}, function (err) {
let elapsed = Date.now() - now;
if (elapsed <= queryTimeout) { // don't handle timeout here
if (err) {
console.log(new Date().toISOString(), 'Query failed:', err, ', ms:', elapsed);
} else {
// if (elapsed > 10) {
console.log(new Date().toISOString(), 'Query successful in ms:', elapsed);
// }
}
clearTimeout(timeout);
setTimeout(startQuerying, queryBackoff, db);
}
});
}
MongoClient.connect(connUri, connOpts, function (err, db) {
startQuerying(db);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment