1

How can I run child_process commands on MongoShell from Node.js? I have the following code and it only executes the mongo command. Nothing after that.

const util = require("util");
const exec = util.promisify(require("child_process").exec);

async function linuxCommand(command) {
  try {
    const { error, stdout, stderr } = await exec(command);
    if (stderr) {
      console.log("stderr: ", stderr);
      return;
    }
    console.log("stdout: ", stdout);
    return stdout;
  } catch (e) {
    return;
  }
}

async function createDB(data) {
  const dbName = data.db;
  const user = data.userName;
  const pass = data.password;

  await linuxCommand(`mongo`);
  await linuxCommand(`use ${dbName}`);
  await linuxCommand(`db.createUser(
      {
        user: "${user}",
        pwd: "${pass}",
        roles: [ { role: "readWrite", db: "${dbName}" } ]
      })`);

  await linuxCommand("exit");
  console.log("Done");
}

let data = {
  db: "helloThere",
  userName: "hello",
  password: "hello",
};

async function test() {
  await createDB(data);
}
test();

If this does not work like this then how can I create and drop new user in mongoDB in local database, not like creating a user in admin database and giving read/write access to local db. I want the user to be created in local db itself.

darebe8092
  • 11
  • 1
  • You want to get the result of a system call, this is already answered: https://stackoverflow.com/questions/20643470/execute-a-command-line-binary-with-node-js – Mário Aug 21 '20 at 21:26
  • I want to execute commands in mongo shell. I know the normal terminal commands can be executed as you mentioned in the link. But the mongo shell command is not being executed. – darebe8092 Aug 21 '20 at 21:32

0 Answers0