简体   繁体   中英

MongoDB: How to call a function defined in another JS file?

I have a function defined called func1 in file file_a.js

I have another file file_b.js , in which I want to use the function func1 . Can I do this inside mongo environment?

Amended answer thanks to AD7six Mongodb console can take multiple input file loaded in order specified.

Or you can use the built in load function like this

➜  mongotest  cat test.js
load("test2.js");
print("test.js");
foo();
➜  mongotest  cat test2.js
var foo = function() {
  print("test2.js");
};

➜  mongotest  mongo test.js
MongoDB shell version: 2.0.6
connecting to: test
test.js
test2.js

test.js is the file given to mongodb console, it loads test2.js(containing function foo) and calls foo

If you are meaning via the cli (are you?), you can load multiple js files via the mongo shell

$ mongo --help
MongoDB shell version: 2.0.6
usage: mongo [options] [db address] [file names (ending in .js)]

Note file name s

Therefore, you can just load both files, and the contents of file_a will be available to file_b:

mongo [args] dbname file_a.js file_b.js

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