简体   繁体   中英

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, eg 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.

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.

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, eg

mongo --shell mymongohost:port/myDB myjsfunctions.js

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM