Executing JavaScript file in MongoDB - javascript

I would like to know how to execute a JavaScript file in MongoDB.
This is the simple piece of code present in my JS file:
function loadNames() {
print("name");
}
From the command prompt I tried to execute the file like this
mongo test.js
but it shows the error:
unexpected identifier
Can anyone explain to me where I'm going wrong?

I usually run my test queries like this, and it works with your sample code too.
mongo < test.js

two meothods to achieve this:
1 . use "--eval"
mongo quickstats_db --eval "printjson(db.getCollectionNames())"
2 . execute the js file
mongo quickstats_db print.js
where content of print.js is:
printjson(db.getCollectionNames())

From mongo --help, we got:
$ mongo --help
MongoDB shell version v3.6.2
usage: mongo [options] [db address] [file names (ending in .js)]
db address can be:
foo foo database on local machine
192.168.0.5/foo foo database on 192.168.0.5 machine
192.168.0.5:9999/foo foo database on 192.168.0.5 machine on port 9999
Options:
--shell run the shell after executing files
--nodb don't connect to mongod on startup - no
'db address' arg expected
--norc will not run the ".mongorc.js" file on
start up
--quiet be less chatty
--port arg port to connect to
--host arg server to connect to
--eval arg evaluate javascript
-h [ --help ] show this usage information
... ...
and referred mognodb's tutorial/document, we got this script named as my-mongo-script.js:
'use strict';
// #see https://docs.mongodb.com/manual/tutorial/write-scripts-for-the-mongo-shell/
var MONGODB_URI = "mongodb://127.0.0.1:27020/testdb";
var db = connect(MONGODB_URI);
var collections = db.getCollectionNames();
print(collections.join('\n'));
printjson(collections);
so this cmd mongo --nodb my-mongo-script.js will execute the script.
You can add a "--shell" like mongo --nodb --shell my-mongo-script.js to "run the shell after executing files".

Related

get terminal response and store it as a variable in node js

In the middle of my Node.js file I want to store the terminal response of docker run -v ${PWD}/app.py:/app.py proj1part1dockerimage in my file and store the output as a var. How would i go about getting a terminal response without opening a terminal?
In node.js everything is asynchronous, so you have to use a callback:
child_process.exec("docker run -v ${PWD}/app.py:/app.py proj1part1dockerimage",
(err, stdout, stderr) => {
const output = stdout.toString();
}
)
But if you require it to be instant which I don't recommend:
const output = child_process.execSync("docker run -v ${PWD}/app.py:/app.py proj1part1dockerimage").toString();

How to resolve the error while executing top command using node child_process.exec?

I am trying to execute a bunch of bash commands using node.js. I used child_process.exec to execute the commands.
var child_process = require('child_process');
child_process.exec("ps -p $(lsof -ti tcp:8088) o pid=,comm=",function(err,stdout, stderr){
if(err){
console.log('error',err);
return;
}
console.log('stdout', stdout);
});
This will list the process id running in the port 8088 along with name. In the similar way when i try to execute top command with a process id to check cpu and memory utilization. I am facing an error.
var execTop = function(pid){
child_process.exec("top -p 12769", function(err, stdout, stderr){
if(err){
console.log('error',err);
return;
}
console.log("top output",stdout);
})
}
I couldn't find much resource online to clarify this issue. The actual error is
error { [Error: Command failed: /bin/sh -c top -p 12769
top: failed tty get
]
killed: false,
code: 1,
signal: null,
cmd: '/bin/sh -c top -p 12769' }
I appreciate the possible solutions suggested. Thanks in advance.
If you really want to run top like this, you need to run in it "Batch Mode", like:
top -b -n 1 -p 12345
This is because top is usually meant to be an interactive command and wants to have an actual terminal to write to. You might want to consider using something like ps u -p 12345 for more concise output.
as Grisha suggested, use the 'Batch Mode' and if only cpu and memory is needed, for default top output I'd use something like:
top -b -n 1 -p 12345 | awk '{if(NR>7)print $9,$10}'

JavaScript file can't work while the code work with node in Terminal

I start a java client listening on localhost:8887
And I try this
var net = require('net')
var coon = net.connect(8887,'127.0.0.1')
coon.write('hi')
coon.destroy()
in Terminal with node. The client get the message.
Then I write it into a file test.js and use 'node test.js' in the Terminal, but the client can't get the message. How can I solve this problem.
I add
console.log(coon.remoteAddress+':'+coon.remotePort)
in the code. When I run 'node test.js', it shows that 'undefined:undefined'
Chances are you type into the terminal slow enough for the connection to be made. When you run the whole script, you're attempting to write before there is a connection.
Use the 3rd connectionListener argument
const coon = net.connect(8887, 'localhost', () => {
coon.write('hi');
coon.destroy();
});
See https://nodejs.org/api/net.html#net_net_connect_port_host_connectlistener

knex.js not returning when using from nodejs script

I'm using knex.js as ORM in a nodejs script but when I run it from command line the script "freezes" and doesn't end like it used to before adding knex in it:
~/dir $ node index.js projects read-all
freeze
adadazdzadad
^C
~/dir $
Thus I have no choice but use Ctrl+C everytime to exit the script and I want to avoid that and end the script in a clean way. But how ?
index.js
var args = require('yargs').argv;
var knex = require('knex')({
client: 'sqlite3',
connection: {
filename: './data.db'
}
});
console.log(args);
Adding knex.destroy(); at the end of the script solved the problem.

Execute javascript on mongo command line with Authorization

I have been successfully executing javascripts from the mongo shell
We have now enabled authorization on the mongo database
The permissions have been given and if I login to the shell and execute queries everything is fine
However, I am trying to execute the javascript from command line and I have a problem
I am issuing the command
mongo -u -p -authenticationDatabase admin GetProcessDate.js
I get the error message
MongoDB shell version: 2.6.5
connecting to: test
2014-10-15T06:44:11.451-0700 error: { "$err" : "not authorized for query on bvmaster.ProcessDate", "code" : 13 } at src/mongo/shell/query.js:131
failed to load: GetProcessDate.js
When I disable authorization this javascript executes just fine
mongo GetProcessDate.js
When I enable authorization and login to the shell everything works fine
mongo -u <user>-p <password> -authenticationDatabase admin
The javascript is a very simple one
mongo = new Mongo();
bvmasternew = mongo.getDB( "bvmaster" );
ProcessDateCursor = bvmasternew.ProcessDate.find();
ProcessDateRec = ProcessDateCursor.next();
print( ProcessDateRec.Date);
Any help will be appreciated!!
After a lot of searchs I found the following;
When you are executing a javascript on the mongo command line, it does not matter what parameters you pass on the command line
inside your mongo javascript
you need to call the mongo with proper parameters
mongo = new Mongo( server:port );
admin = mongo.getDB( "admin" );
admin.auth( User, Password );
These lines basically authorizes the user to perform various operations in that mongo instance you have connected using server/port combination

Categories

Resources