Can I call rs.initiate() and rs.Add() from node.js using the MongoDb driver?
How are the replica set admin helpers implemented?
The rs.*
replica set admin helpers in the mongo
shell are wrappers for MongoDB commands which you can send from any driver.
You can see which command(s) each shell helper wraps by referring to the MongoDB documentation:
rs.initiate()
provides a wrapper around thereplSetInitiate
database command.rs.add()
provides a wrapper around some of the functionality of thereplSetReconfig
database command and the corresponding mongo shell helperrs.reconfig()
.rs.conf()
wraps thereplSetGetConfig
database command.
Note that the mongo
shell helpers may do some extra validation or manipulation of configs as they are intended to be used via the interactive mongo
shell.
You can confirm how any of the shell helpers are implemented by invoking the command in the shell without trailing parentheses, eg:
> rs.initiatefunction (c) { return db._adminCommand({ replSetInitiate: c }); }
Calling replica set database commands from Node.js
The equivalent logic can be implemented via the Node.js driver 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: it doesn't have to be from a node application, if someone knows of another way of getting the same thing done, please share your thoughts.
Rather than reimplementing the replica set helpers in Node.js, you could invoke a mongo
shell with the --eval
command to run the shell helper (tip: include --quiet
to suppress unnecessary messages).
For example, calling from your Node app:
var exec = require('child_process').exec;var rsAdmin = exec('mongo --eval "var res = rs.initiate(); printjson(res)" --quiet', function (error, stdout, stderr) { // output is in stdout console.log(stdout);});