How to "require (module)" in the mongo shell

I am writing a mongo script shell to manage data. I want to write it using modular code that uses function libraries as modules. In some cases, my own modules. In other cases, carefully selected node.js modules (which, as I know, will work in the Mongo shell environment, such as uuid).

Unfortunately, Mongo does not have real module control. load () is not the same thing. I am looking for something filled.

Does anyone know a library that can provide CommonJS module loading functionality that is common enough to work in the Mongo shell or ported to run in the Mongo shell?

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

+6
source share
2 answers

Well, there are some tips to make it work.

Firstly, if your CommonJS module does not need a module, it is simple:

var module = {}; load('/lib/migration/forms.js'); print(typeof module.exports); 

Secondly, if your module needs others, you need to create one module with a browser and require it as in the example above.

+2
source

No. The mongo shell is a proprietary javascript engine running on a V8 engine. You cannot load Node.js modules into the mongo shell more than you can in a browser. Many Node features will simply not be part of the mongo shell environment. You can use the Node.js driver in Node.js so that you can use your Node modules, or you can try to get the necessary bits in a js file that you can run to configure the appropriate environment when the shell starts, for example

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

Source: https://habr.com/ru/post/974562/


All Articles