Skip to content

Instantly share code, notes, and snippets.

@aheckmann
Created October 31, 2012 17:03
Show Gist options
  • Save aheckmann/3988326 to your computer and use it in GitHub Desktop.
Save aheckmann/3988326 to your computer and use it in GitHub Desktop.
/**
* first connect to mongo and start up a test replica set with auth:
*
* mongo
* > var t = new ReplSetTest({ nodes: 3, keyFile: '/data/keyfile' })
* > t.startSet()
* > t.initiate();
*
* in another shell, connect to the replset.
* add an admin user
* add a user with only access to the test db (in this case its "boring:boring")
* run this script.
* notice that we get objectids and document counts logged to the console.
* while this is running, get the replset into a situation where there is no master
*
* > t.stop(nodeNumber, true); // stops a node
* > t.start(nodeNumber, true, true); // restarts the node
*
* I'll see the following error during elections:
*
* Error: No replica set member available for query with ReadPreference primaryPreferred and tags undefined
* at pickFirstConnectedSecondary (/Users/aaronheckmann/test/node-mongodb-native/lib/mongodb/connection/repl_set.js:875:10)
* at _roundRobin (/Users/aaronheckmann/test/node-mongodb-native/lib/mongodb/connection/repl_set.js:1052:12)
* at ReplSet.checkoutReader (/Users/aaronheckmann/test/node-mongodb-native/lib/mongodb/connection/repl_set.js:991:22)
*
* **More importantly**, observe that this script no longer outputs any query results when there is no master available.
*/
var mongo = require('mongodb')
var assert =require('assert')
// connection strings
var conn = 'mongodb://boring:boring@localhost:31000,localhost:31001,localhost:31002/test';
//var conn = 'mongodb://admin:admin@localhost:31000,localhost:31001,localhost:31002/test';
//var conn = 'mongodb://localhost:31000,localhost:31001,localhost:31002/test';
// read prefs
var pref = 'primaryPreferred'
//var pref = 'secondary'
//var pref = 'primary'
//var pref = 'secondaryPreferred'
// options
var opts = { db: {readPreference: pref } };
//opts = {};
// test
mongo.Db.connect(conn, opts, function (err, db) {
assert.ifError(err);
var stuff = db.collection('stuff');
stuff.insert({ name: 'testing' }, function (err) {
setInterval(query(), 1500);
});
var i = 0;
function query () {
//stuff.insert({ name: i++ }, function (err) {
//if (err) log(err);
//});
var opts = { read: pref };
opts = {};
stuff.findOne({}, opts, function (err, doc) {
if (err) log(err);
if (doc) console.log(doc._id);
})
stuff.count({}, opts, function (err, count) {
if (err) log(err);
console.log('total docs: %d', count);
})
return query;
}
function log (err) {
console.error('=====================================');
console.error(err.stack);
console.error('=====================================');
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment