Skip to content

Instantly share code, notes, and snippets.

@saintc0d3r
Created July 13, 2014 06:54
Show Gist options
  • Save saintc0d3r/7f3d2191669a627fdfb6 to your computer and use it in GitHub Desktop.
Save saintc0d3r/7f3d2191669a627fdfb6 to your computer and use it in GitHub Desktop.
[MongoDb][Node.js] A simple demo of read preference settings when reading documents from a replica set
/**
* A sample demo to demonstrate Read Preference settings when reading data from a replica set.
* Instructions:
* 1. Run your replica set servers.
* 2. Run this app (note: adjust the replica set's hosts & ports as you see them fit in your environments.)
* 3. Shutdown your replica set's primary node.
* 4. Watch the outputs of this running app. Confirm that the findOne were defered ( no errors being throws) when the primary node is downed and
* then come up again after a new primary node is elected in the replica set.
*/
var MongoClient = require('mongodb').MongoClient;
var ReadPreference = require('mongodb').ReadPreference;
var assert = require('assert');
// We'll set the read preference so that by default, this program would read data directly from secondary node in the replica set
var connection_string = "mongodb://KURONO:27018, KURONO:27019, KURONO:27020/demo_replica_set?readPreference=secondary";
MongoClient.connect(connection_string, function(err, db){
if (err) throw err;
// Insert a test document
var test_doc = {'value': Math.random()};
var test_docs = db.collection("test_docs");
test_docs.insert(test_doc, function(err, insertedDoc){
if (err) throw err;
assert.ok(insertedDoc.length > 0);
console.log("[INFO] - Successfully inserted "+JSON.stringify(insertedDoc)+" document.");
function findOneDocument(){
// Override the default setting so that the next read would goes to Primary node in the replica set.
var read_preference = {'readPreference': ReadPreference.PRIMARY };
test_docs.findOne({_id: insertedDoc[0]._id},read_preference, function(err, foundDoc){
if (err) throw err;
//assert.ok(foundDoc.length > 0);
console.log("[INFO] - Retrieved document: "+ JSON.stringify(foundDoc) + " where the read preference is "+JSON.stringify(read_preference));
});
console.log("[INFO] - Dispatched findOne operation...");
// Delayed for 1 sec then dispatch another insert.
setTimeout(findOneDocument, 1000);
}
findOneDocument();
});
});
@4Z4T4R
Copy link

4Z4T4R commented Jul 29, 2017

@ejazmafat999 - I'm hoping you figured it out by now, but you need to initialize your replicaSet.

mongo > rs.initialize();

Then, make it ok for the current replica to slave:

mongo > rs.slaveOk()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment