Can I call rs.initiate () and rs.Add () from node.js using the MongoDb driver?

I'm looking to automate the process of configuring a MongoDb replica set through a stroller when using Docker and Kubernetes.

The above setup is not very important , which boils down to the fact that I need to be able to invoke mongo replica set commands (for example, rs.initiate() , rs.add('anotherserver') , rs.conf() , rs.reconfig() etc.) from the node.js. application

Note: this should not be from the node application, if someone knows about another way to do the same, please share your thoughts.

UPDATE: I was able to get this working and made sidecar open source for other users.

+6
source share
1 answer

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) { // output is in stdout console.log(stdout); }); 
+10
source

Source: https://habr.com/ru/post/986535/


All Articles