1

I have two Mongodb shell scripts written in js. Both are sharing some code between them. Is it possible to extract that code to another file and to import it from there? And how?

I have been trying with require / import but that obviously not working, also tried with load() but no success.

I know it is using the SpiderMonkey js engine, but no idea if it is possible.

U Rogel
  • 1,893
  • 15
  • 30
  • https://docs.mongodb.com/manual/tutorial/write-scripts-for-the-mongo-shell/#execute-a-javascript-file – ISAE May 05 '21 at 15:35

1 Answers1

0

Yes! The solution is .mongorc.js file at your home directory.

Check documentation here!

JJussi
  • 1,540
  • 12
  • 12
  • Can you please elaborate a bit or give an example? – U Rogel May 06 '21 at 06:47
  • Whatever code you put in .mongorc.js -file (in your home directory) it is loaded when you start mongo. So, you extract that code (what is shared) as a function/procedure and put it there. All scripts (.js) can use it. – JJussi May 06 '21 at 12:23
  • So it is globally defined? like the `db` variable? – U Rogel May 06 '21 at 13:56
  • Not... Really. That file can have one or more function(s) and/or procedure(s) what you can use/call inside mongo - when you run it as a command tool or when you run some other .js code with it. – JJussi May 06 '21 at 22:53