Call a java script file in mongodb shell - javascript

I tried to run a JS file directly from the Mongo shell by using the query
mongo localhost:27017/west createSumCollection.js
However I keep getting the error
"uncaught exception: SyntaxError: unexpected token: identifier :
#(shell):1:6"
The contents of CreateSumCollection.js are a simple use database and db.createCollection with a simple object id and another field.
Any idea what I am missing here? If I run the same script in the mongoshell directly it works perfectly.
I tried load("C:/mongodb/data/db/createSumCollection.js") and it failed because of the use west statement inside the .js file. So after removing that, the load worked. My question is what is the difference between load and mongo localhost:27017/west createSumCollection.js and how do i get the js to be run directly.

use is a helper that is only available in the interactive shell.
In the interactive shell (and via load) you might run:
use my_database
db.collection.find()
The equivalent in a javascript file on the command line would be:
db.getSiblingDB("my_database").collection.find()

Related

The term “URL=Test.com” is not recognized

I have the following in my test file. I’m trying to use env variables on my scripts then send the value thru commandline.
const MYURL = process.env.URL;
console.log(MYURL)
In the commandline when I run the following:
URL=Test.com npx playwright test
I get an error message:
The term ‘URL=Test.com’ is not recognized as the name of the cmdlet..etc.
Because you use bash syntax in Powershell. Powershell does not set env variables like var=value, so this syntax won't work.
You probably need to read something like this to figure out the right syntax for Powershell.

How to import a Javascript Object in mongo shell script

I have a shell script file called run.sh
CONNECTION_STRING="mongodb://localhost:27017/"
mongo --nodb --eval "var connectionString=\"$CONNECTION_STRING\"; `cat mongo-initialize.js`"
I'm passing a js fragment to the mongo shell. This is my mongo-initialize.js:
conn = new Mongo(connectionString);
db = conn.getDB("dbName");
db.createCollection("collection");
db["collection"].insertMany(data);
The data I'm using to insert into the collection will be a js object which I'm planning to use here and I need it for an API as well. So I created a js file mock.js which has that object and I exported it. The thing is I don't find an appropriate command to import the data in my mongo-initialize.js.
The only command MongoDB docs suggest is load('someFile.js') which is not working in my case. As per MongoDB docs, it executes the js file and it throws an error if I try to load it this way.
This function loads and executes the myjstest.js
Is there a way to import a js object into my script file?

How to use Node.js packages within a client-side html document using browserify

I'm unable to use a node.js module on my website with broweserify. The example only shows how to run a javascript file that is separate from the .html file, not how to use the node.js module within the .html file. Seems like a trivial problem, but I'm unable to make it work.
Here's what I've done:
Initialized node.js & installed a package, npm i webtorrent-health as an example
Created require_stuff.js which consists of a single line: var WebtorrentHealth = require('webtorrent-health')
Run browserify: browserify require_stuff.js > bundle.js
Include package in my html document, e.g. <script src='bundle.js'></script>
Use the package somewhere in my document, e.g. like this: <script>webtorrentHealth(magnet).then(foobazbar())</script>
Despite bundle.js executing and seemingly defining webtorrentHealth, the script within the .html document fails with WebtorrentHealth is not defined. What am I doing wrong? How do I make it work? Thank you!
You're very close to what you want to achieve. In fact, your code bundle.js is inaccessible from outside (in your case the browser) due to browserify, but you can expose your module by writing at the end of your file require_stuff.js:
window.WebtorrentHealth = WebtorrentHealth;
Now you can use WebtorrentHealth in your document.

Require is not working for node-opcua

I want to load a local version of node-opcua with 'require' inside a HTML file, but it does not really work. The code snippet is the following:
<script type="text/javascript" src="path_to_require.js"></script>
<script>
var opcua = require(["path_to_node-opcua"]); <!-- Yes, the path is correct >
var client = new opcua.OPCUAClient();
...
When I execute the script I get the following error in the console:
Uncaught TypeError: opcua.OPCUAClient is not a constructor
Hence, var opcua is loaded correctly, but OPCUACluent is not, although the class is declared in a file that is present in the node-opcua folder called opcua_client.js under node-opcua\lib\client\
Sources:
The 'require' script from http://requirejs.org/docs/download.html#requirejs.
The node-opcua folder with the console command
npm install node-opcua.
node-opcua is not intended to run inside a browser as it relies on nodejs specific features such as filesystem access, crypto and so on.
You need to use browserify if you want to use that module in client. You will also need to look at how to use browserify with file system access (it can be done if paths are known ahead of time).

How do I handle command-line arguments in a mongo script?

I've been working on some simple scripts to run on mongo from the bash command-line. Originally, I ran them as follows:
$ mongo dbname script.js
but I recently came across mikemaccana's answer, https://stackoverflow.com/a/23909051/2846766, indicating the use of mongo as an interpreter so I can just execute script.js (or any name I choose, with or without the .js) from the command line.
$ script.js
I think it's brilliant and clean, but now I'd like to pass in a database name as a command line argument.
$ script.js dbname
Here I use the bash-style "$1" to demonstrate what I'm doing in script.js.
#!/usr/bin/env mongo
var db = new Mongo().getDB($1);
// Do other things with db, once I resolve the name from the command line.
This results in a "ReferenceError: $1 is not defined ...", which is not surprising. But how would I reference command line arguments? Is this going to be a mongo convention? a javascript convention? Is it possible? It would make my command-line experience with mongo much better aesthetically.
Currently there is no way to do this using the mongo shell...
https://groups.google.com/forum/#!topic/mongodb-user/-pO7Cec6Sjc
... try using a bash script (or other scripting language you are comfortable with) if you want to get a similar command line experience.
Duplicate of How to pass argument to Mongo Script
In a nutshell, this is not possible but several workarounds are given in the answers (not repeated here).
You can pass args to your script through
mongo --eval 'var databasePassword="password"' script.js
and you can access databasePassword value inside script.js
db.auth({ user: 'testUser, pwd: databasePassword });

Categories

Resources