Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "require(module)" in mongo shell

I am writing a mongo shell script for data management. I want to write it using modular code that makes use of function libraries as modules. In some cases, my own modules. In other cases, carefully selected node.js modules (that I know will work in the Mongo shell environment, e.g. uuid).

Unfortunately, Mongo lacks real module management. load() is not the same thing. I'm looking for a back-fill, as it were.

Does anybody know of a library that can provide CommonJS module loading functionality, that is generic enough to run in the Mongo shell, or that has been ported to run in the Mongo shell?

Yes, I know, I could just do it in a purely node.js environment. But if there is such a thing as a real module loader that will work in the mongo shell, that would be my first choice.

like image 472
John Arrowwood Avatar asked Aug 29 '14 19:08

John Arrowwood


Video Answer


2 Answers

Well, there are some tips to get it working.

The first, if your CommonJS module requires no module is a simple as:

var module = {};

load('/lib/migration/forms.js');

print(typeof module.exports);

The second, if your module requires others is to build a single module with browserify and require it like in the above example.

like image 164
nfroidure Avatar answered Oct 20 '22 21:10

nfroidure


No. The mongo shell is its own javascript environment running the V8 engine. You can't load in Node.js modules into the mongo shell anymore than you can into the browser. A lot of Node functions just won't be part of the mongo shell environment. You can either use the Node.js driver in Node.js so you can use your Node modules, or you can try to get the necessary bits into a js file that you can run to set up the appropriate environment when you run the shell, e.g.

mongo --shell mymongohost:port/myDB myjsfunctions.js
like image 25
wdberkeley Avatar answered Oct 20 '22 22:10

wdberkeley