How are replica set admin assistants implemented?
rs.* set of replica helper mongo in the mongo shell are shells for MongoDB commands that you can send from any driver.
You can see which command (s) wraps the shell using the MongoDB documentation:
Note that mongo shell mongo may perform some additional validation or configuration processing, as they are intended to be used through the mongo interactive shell.
You can confirm how any of the shell helpers is implemented by calling a command in the shell without end brackets, for example:
> rs.initiate function (c) { return db._adminCommand({ replSetInitiate: c }); }
Calling replica database commands with Node.js
Equivalent logic can be implemented using the Node.js API using command() :
// Rough equivalent of rs.initiate() var MongoClient = require('mongodb').MongoClient; MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { // Use the admin database for commands var adminDb = db.admin(); // Default replica set conf var conf = {}; adminDb.command({replSetInitiate: conf}, function(err, info) { console.log(info); }); });
Note: this should not be from the node application, if someone knows about another way to do the same, please share your thoughts.
Instead of reimplementing replica sets in Node.js, you can invoke the mongo shell with the --eval to launch the shell helper (tip: include --quiet to suppress unnecessary messages).
For example, a call from your node application:
var exec = require('child_process').exec; var rsAdmin = exec('mongo --eval "var res = rs.initiate(); printjson(res)" --quiet', function (error, stdout, stderr) {