'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.



Solution 1:[1]

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.

Solution 2:[2]

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

Solution 3:[3]

While the legacy mongo shell does not support node modules via the require statement, the new mongosh shell does. You will need to install it via the 5.0 MongoDB repo but it is compatible with any database from 4.0 and above.

Reference here: https://www.mongodb.com/docs/mongodb-shell/write-scripts/require-external-modules/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 nfroidure
Solution 2 wdberkeley
Solution 3 SylonZero