1

My .js script reads from a file containing mongodb queries and populates it into an array. Then I read that array and executing the queries but they are not being executed. Below is my code.

1. //After successfuly connecting to mongodb
2. //read a file containing queries
3. var queryFile = cat("queries.txt");
4. var queries = queryFile.split("\r\n");
5. var length = queries.length;
6. for(var i = 0; i < length; i++){
7.        var start = new Date().getTime()
8.        queries[i]
9.        var end = new Date().getTime();
10.        var timeElapsed = (end - start)/1000;
11.        print ( "Time taken to run query : "+timeElapsed+" secs" )
12. }

It only works if I replace line 12 with an actual query e.g. db.coll.count()

5
  • queries[i] is just a string. My guess would be to evaluate that string with eval(queries[i]). Even if 'eval is evil' and stuff. Commented Jun 15, 2016 at 12:19
  • Okay that did the trick, but why is eval evil. Commented Jun 15, 2016 at 12:23
  • Oh it's an old debate. Basically, eval allows code injection, by running whatever's passed to it. Look at this and that Commented Jun 15, 2016 at 13:20
  • Great, can you draft an answer then I will accept that. Commented Jun 16, 2016 at 8:59
  • Good idea :) Did so. Commented Jun 16, 2016 at 9:17

1 Answer 1

2

queries[i] is just a string. It's a stringified instruction. My guess would be to evaluate it with eval(queries[i]).

for(var i = 0; i < length; i++){
        var start = new Date().getTime()
        eval(queries[i]);
        var end = new Date().getTime();
        var timeElapsed = (end - start)/1000;
        print ( "Time taken to run query : "+timeElapsed+" secs" )
 }

However, one often says that eval is evil and has to be used ONLY in last resort.

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

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.