I'm looking to automate the process of setting up a MongoDb replica set via a sidecar when using Docker and Kubernetes.
The above setup isn't terribly important, what it boils down to is that I need to be able to call the mongo replica set commands (e.g. rs.initiate()
, rs.add('anotherserver')
, rs.conf()
, rs.reconfig()
, etc) from a node.js application.
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.
UPDATE: I was able to get this working and have made the sidecar open source for others to use.
How are the replica set admin helpers implemented?
The
rs.*
replica set admin helpers in themongo
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 interactivemongo
shell.You can confirm how any of the shell helpers are implemented by invoking the command in the shell without trailing parentheses, eg:
Calling replica set database commands from Node.js
The equivalent logic can be implemented via the Node.js driver API using
command()
: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: