Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run javascript script (.js file) in mongodb including another file inside js

Tags:

mongodb

I want to write a long script for inserting and updating mongodb data.

  1. Is it possible to call external js file that contains the script?
  2. Is it possible to include another js file from the running js file?
like image 971
SexyMF Avatar asked Mar 07 '14 11:03

SexyMF


People also ask

How do I include an external js file in another JavaScript file?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file.

How do I run a JavaScript script in MongoDB?

Execute a JavaScript file js script in a mongo shell that connects to the test database on the mongod instance accessible via the localhost interface on port 27017 . Alternately, you can specify the mongodb connection parameters inside of the javascript file using the Mongo() constructor.

Can I use JavaScript in MongoDB?

MongoDB is a document-based NoSQL database that stores data in BSON (JSON-like) format. JavaScript is unanimously the most popular language for building web applications. It can also be used for building server-side applications usingNode. js.

Can JavaScript be in a separate file?

You can keep the JavaScript code in a separate external file and then point to that file from your HTML document.


3 Answers

Use Load function

load(filename)

You can directly call any .js file from the mongo shell, and mongo will execute the JavaScript.

Example : mongo localhost:27017/mydb myfile.js

This executes the myfile.js script in mongo shell connecting to mydb database with port 27017 in localhost.

For loading external js you can write

load("/data/db/scripts/myloadjs.js")

Suppose we have two js file myFileOne.js and myFileTwo.js

myFileOne.js

print('From file 1');
load('myFileTwo.js');     // Load other js file .

myFileTwo.js

print('From file 2');

MongoShell

>mongo myFileOne.js

Output

From file 1
From file 2
like image 58
Sumeet Kumar Yadav Avatar answered Oct 07 '22 04:10

Sumeet Kumar Yadav


Another way is to pass the file into mongo in your terminal prompt.

$ mongo < myjstest.js

This will start a mongo session, run the file, then exit. Not sure about calling a 2nd file from the 1st however. I haven't tried it.

like image 10
YeeHaw1234 Avatar answered Oct 07 '22 06:10

YeeHaw1234


Yes you can. The default location for script files is data/db

If you put any script there you can call it as

load("myjstest.js")      // or 
load("/data/db/myjstest.js")
like image 7
Toumi Avatar answered Oct 07 '22 06:10

Toumi