1

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);
1
  • For further information look at this answer Commented Sep 15, 2023 at 12:45

2 Answers 2

1

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);

})
Sign up to request clarification or add additional context in comments.

9 Comments

Thank you, but where are you executing line_to_execute ? its not working
I added some comments to make it more clear. The eval call should be executing the line_to_execute
Eval doesn't execute the query. It's not expression correct
What do you mean by it is not expression correct ? It should be able to run any valid js expression. Even those doing queries to the database.
No . Please try a sample program to run above script and let me know.
|
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.