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.