MongoDB Shell Script on Replica Set - javascript

I'm trying to run a javascript file against a mongodb replica set but it fails on line 2 with the following error:
MongoDB shell version: 2.4.5
connecting to: test
Tue Jan 21 09:00:01.702 JavaScript execution failed:
ReferenceError: conn is not defined at /opt/mongo-scripts/views-by-date.js:L2
failed to load: /opt/mongo-scripts/views-by-date.js
This is the content of the script:
var conn = new Mongo();
var db = conn.getDB("main"); // line 2
var date = ISODate();
...
This is the command I'm running on the bash shell:
mongo /opt/mongo-scripts/views-by-date.js
I'm assuming, though may well be wrong, it has something to do with it being a replica set as the script works on my local non-replica set mongo instance.

This should do the trick:
Remove first line
Change second line to var db = db.getSisterDB("main")

Related

NextGen (Mirth) Connect & MongoDB java driver error

I am trying to configure Mirth Connect Server 3.10.1 (Java version: 1.8.0_181), to write FHIR JSON docs to MongoDB. I've followed instructions from this post and have these drivers in custom-lib/
bson-4.2.0.jar
mongodb-driver-3.9.1.jar
mongodb-driver-core-4.2.0.jar
My conf/dbdrivers.xml has an entry like this,
<driver class"org.mongodb.Driver" name="MongoDB" template="mongodb://localhost:27017/" selectLimit="" />
I've setup my Channel Destination with a JavaScript Writer Connector Type and used this JS,
var mongoClient = new Packages.com.mongodb.MongoClient("localhost", 27017);
var database = mongoClient.getDatabase("synthea");
var collection = database.getCollection("synthea");
var jsonDoc = JSON.stringify(connectorMessage.getEncodedData(msg));
var doc = Packages.org.bson.Document.parse(jsonDoc);
collection.insertOne(doc);
var myDoc = collection.find().first();
logger.debug(myDoc.toJson());
mongoClient.close();
return;
When I deploy the Channel, I am getting this error.
Can anyone tell me what this means?
Any help or guidance very much (and humbly) appreciated.
JavaScript Writer error
ERROR MESSAGE: Error evaluating JavaScript Writer
java.lang.NoSuchMethodError: 'com.mongodb.connection.ConnectionPoolSettings$Builder com.mongodb.connection.ConnectionPoolSettings$Builder.maxWaitQueueSize(int)'
at com.mongodb.MongoClientOptions.<init>(MongoClientOptions.java:149)
at com.mongodb.MongoClientOptions.<init>(MongoClientOptions.java:57)
at com.mongodb.MongoClientOptions$Builder.build(MongoClientOptions.java:1612)
at com.mongodb.MongoClient.<init>(MongoClient.java:155)
at com.mongodb.MongoClient.<init>(MongoClient.java:145)
at jdk.internal.reflect.GeneratedConstructorAccessor135.newInstance(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
at org.mozilla.javascript.MemberBox.newInstance(MemberBox.java:171)
at org.mozilla.javascript.NativeJavaClass.constructInternal(NativeJavaClass.java:268)
at org.mozilla.javascript.NativeJavaClass.constructSpecific(NativeJavaClass.java:207)
at org.mozilla.javascript.NativeJavaClass.construct(NativeJavaClass.java:169)
at org.mozilla.javascript.Interpreter.interpretLoop(Interpreter.java:1713)
at org.mozilla.javascript.Interpreter.interpret(Interpreter.java:1009)
at org.mozilla.javascript.InterpretedFunction.call(InterpretedFunction.java:109)
at org.mozilla.javascript.ContextFactory.doTopCall(ContextFactory.java:412)
at org.mozilla.javascript.ScriptRuntime.doTopCall(ScriptRuntime.java:3545)
at org.mozilla.javascript.InterpretedFunction.exec(InterpretedFunction.java:121)
at com.mirth.connect.server.util.javascript.JavaScriptTask.executeScript(JavaScriptTask.java:150)
at com.mirth.connect.connectors.js.JavaScriptDispatcher$JavaScriptDispatcherTask.doCall(JavaScriptDispatcher.java:230)
at com.mirth.connect.connectors.js.JavaScriptDispatcher$JavaScriptDispatcherTask.doCall(JavaScriptDispatcher.java:190)
at com.mirth.connect.server.util.javascript.JavaScriptTask.call(JavaScriptTask.java:113)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
at java.base/java.lang.Thread.run(Thread.java:832)
I have a feeling this is due to the mismatched driver versions. Version 3.9 has the method indicated in the error, but 4.2 does not.
Once you get that sorted out, you are going to want to change this line
var jsonDoc = JSON.stringify(connectorMessage.getEncodedData(msg));
to this
var jsonDoc = connectorMessage.getEncodedData();
msg does not exist in a Javascript Writer, and connectorMessage.getEncodedData() does not take any parameters and returns a String. connectorMessage is an instance of ImmutableConnectorMessage from the Mirth User API.

Improper parsing of strings

I'm trying to convert ansi color codes from console output into HTML. I have a found a script to do this but I cant seem to make it parse the strings inside node js. I have tried to JSON.stringify it to also include special chars but its not working.
forever list
[32minfo[39m: Forever processes running
[90mscript[39m [37mforever[39m [37mpid[39m [37mid[39m
[90mdata[39m: [37m [39m [37muid[39m [90mcommand[39m
I get output like this back from ssh2shell in node js. I have a script:
https://github.com/pixelb/scripts/blob/master/scripts/ansi2html.sh
This is supposed to convert the above to html and add the appropriate color codes. It works fine with normal terminal output for example:
npm install --color=always | ansi2html.sh > npminstall.html
This is the raw output on the linux machine piped to a file. It seems the JS strings are missing these escapes when they are shown in console.log but they are also missing newlines there. Perhaps its because im concatenating them directly into the string and its removing special chars?
total 24
-rwxr-xr-x 1 admin admin 17002 May 13 02:52 ^[[0m^[[38;5;34mansi2html.sh^[[0m
drwxr-xr-x 4 admin admin 4096 May 13 00:00 ^[[38;5;27mgit^[[0m
-rw-r--r-- 1 admin admin 0 May 13 02:57 ls.html
Hopefully some of this makes sense.
Thanks
There are a couple of filters that SSH2shell applies to the output from commands. The first removes non-standard ASCII from the response and then the colour formatting codes are removed.
In v1.6.0 I have added pipe()/unpipe(), the events for both and exposed the stream.on('data', function(data){}) event so you can access the stream output directly without SSH2shell interacting with it in any way.
This should resolve the problem of not getting the right output from SSH2shell by giving you access to the raw data.
var fs = require('fs')
var host = {
server: {
host: mydomain.com,
port: 22,
userName: user,
password: password:)
},
commands: [
"`Test session text message: passed`",
"msg:console test notification: passed",
"ls -la"
],
}
//until npm published use the cloned dir path.
var SSH2Shell = require ('ssh2shell')
//run the commands in the shell session
var SSH = new SSH2Shell(host),
callback = function( sessionText ){
console.log ( "-----Callback session text:\n" + sessionText);
console.log ( "-----Callback end" );
},
firstLog = fs.createWriteStream('first.log'),
secondLog = fs.createWriteStream('second.log'),
buffer = ""
//multiple pipes can be added but they wont be bound to the stream until the connection is established
SSH.pipe(firstLog).pipe(secondLog);
SSH.on('data', function(data){
//do something with the data chunk
console.log(data)
})
SSH.connect(callback)
tried this ?
https://github.com/hughsk/ansi-html-stream
var spawn = require('child_process').spawn
, ansi = require('ansi-html-stream')
, fs = require('fs')
var npm = spawn('npm', ['install', 'browserify', '--color', 'always'], {
cwd: process.cwd()
})
var stream = ansi({ chunked: false })
, file = fs.createWriteStream('browserify.html', 'utf8')
npm.stdout.pipe(stream)
npm.stderr.pipe(stream)
stream.pipe(file, { end: false })
stream.once('end', function() {
file.end('</pre>\n')
})
file.write('<pre>\n');

Using sql.js in an Electron application

I am new to Electron. It's pure awesome, and getting started is super fun and easy. For some time now I have been trying to find a "database" solution to use in my application. Of course there is the Web SQL/local storage options, but I am trying to use SQLite. I found sql.js, which is great and easy to use. I could get everything to run correctly put I cannot save/update the database file!
Here is the code:
var remote = require('remote'),
fileSystem = remote.require('fs'),
sql = remote.require('./nodeModules/sql.js'),
database = new sql.Database(fileSystem.readFileSync('./database.sqlite'));
database.run('CREATE TABLE IF NOT EXISTS products (ID integer primary key autoincrement, name text, price integer, stock integer)');
// Save the data back to the file
var data = database.export();
var buffer = new Buffer(data);
fileSystem.writeFileSync("./database.sqlite", buffer);
But I am getting this error from "Buffer": Uncaught TypeError: must start with number, buffer, array or string. Have you run across this issue before ?
I was unable to reproduce this issue on node v6.2.2 (npm v3.9.4) on Windows 10 and OS X 10.11.5. The code is nearly identical to yours:
fs.writeFileSync("filename.sqlite", new Buffer(db.export()));
Check out this repo for more information:
https://github.com/codewisdom/electron-sqljs
I believe you have to read and write the database to the folder returned by calling:
electron.app.getPath('userData')
I created an example project showing how to use sql.js in Electron.

MongoDB, create script for mongo shell

I new to Mongodb, I tried to find good tutorials but no luck.
2 question:
I have mongo install with data and I want to connect it with js file and play with it
I created a.js file and my firs two line were:
conn = new mongo();
db = conn.getDB("table1");
and I get error ReferenceError: mongo is not defined at a.js
any good tutorials ?
I found the answer and it work fine:
conn = new Mongo();
db = conn.getDB("a");
var c = db.getCollectionNames();
print(c);
When I run the file it print all my collection to the shell
Thanks.

The `.mongorc.js` is not found, but there is one

When I start the mongo client mongo.exe, it prints out the following error:
MongoDB shell version: 2.4.9
connecting to: test
Wed Mar 12 11:15:47.013 In File::open(), CreateFileW for 'C:\Users\Zolt�n\.mongo
rc.js' failed with errno:3 The system cannot find the path specified.
Wed Mar 12 11:15:47.014 In File::len(), GetFileSizeEx for 'C:\Users\Zolt�n\.mong
orc.js' failed with errno:6 The handle is invalid.
Wed Mar 12 11:15:47.015 In File::read(), SetFilePointerEx for 'C:\Users\Zolt�n\.
mongorc.js' tried to set the file pointer to 0 but failed with errno:6 The handl
e is invalid.
>
As you see, my user path is C:\User\Zoltán and the character á is read as an unknown character. I bet this is the problem, why mongo can't find my .mongorc.js.
Is there any way I can explicitly set the path for .mongorc.js. Maybe with a configuration file?
mongo --norc ignores the file, and you're good to go.
Not yet there isn't. There will be a "global" mongorc in future versions. For now you can "fake it" like so:
mongo --norc --shell fake.js
So you tell the shell to ignore looking for .mongorc.js then you pass in a javascript file just like you would if you wanted to run the contents.
The --shell parameter forces the return to "shell" after the file ("fake.js") has been evaluated.
So just put any valid JavaScript in that file and it will be treated like the entries in the standard .mongorc.js.
I was getting the following error:
2017-10-02T12:54:21.435-0500 I STORAGE In File::open(), CreateFileW for 'H:\.mongorc.js' failed with errno:3 The system cannot find the path specified.
I created directories /data/db under the location I was getting the error and it resolved the issue.
H:\>md data
H:\>cd data
H:\data>md db
I was able to connect without any issue once those directories were created.
H:\data>mongo
MongoDB shell version: 3.0.15
connecting to: test
> db.names.insert({'name':'Mahrukh Khan'});
WriteResult({ "nInserted" : 1 })
>
You can simply delete .mongorc.js file using sudo rm .mongorc.js and the problem would be solved.

Categories

Resources