Prasad Kanaparthi
Prasad Kanaparthi

Reputation: 6563

How to run raw MongoDB operations using the db.command() and NodeJS

I've set of new Mongodb scripts for every release and i'm trying to create NodeJS utility to run the scripts by reading from .txt files which are there in folder.

Ex: In 1.txt file i've this command db.getCollection("users").createIndex({ name: 1 }); and i want to run using NodeJS

I've NodeJs program like below

const { MongoClient } = require("mongodb");

const uri = "mongodb:uri";

const client = new MongoClient(uri);

async function run() {
  try {
    await client.connect();

    const db = client.db("employee");
    // I want to run above script like here. How can i do it?
    const result = await db.command({
      dbStats: 1,
    });
    console.log(result);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

Upvotes: 1

Views: 718

Answers (2)

Paulo
Paulo

Reputation: 10441

I feel your .txt file could be a .js file. You would then feed it to your mongodb instance like so mongo < yourFile.js

But if for some reason this can not be done.

Eval

Disclaimer: Please be advised of the security concerned of using eval

I feel what you are looking for is eval.

Your code could simply look like:

const { MongoClient } = require("mongodb");

const uri = "mongodb:uri";


MongoClient.connect(uri, function(err, db){

    const dbo = db.db("test");
    // Here you get your lines from your .txt file
    let line_to_execute = 'dbo.collection("customers").findOne({}, (err, res)=>{console.log(res)});';

    // Launch the execution of line_to_execute
    eval(line_to_execute);

})

Upvotes: 1

Prasad Kanaparthi
Prasad Kanaparthi

Reputation: 6563

Got the solution, we can read from .Json files and pass the cmd like below.

     let userNameIndex = {
        createIndexes: "users",
        indexes: [
            {
                key: { "name": 1 },
                name: "nameIndex"
            }
        ],
        comment: "Prasad test"
    };
    eval(userNameIndex);
    const result = await db.command(userNameIndex);
    console.log(result);

Upvotes: 0

Related Questions