MongoDB, create script for mongo shell - javascript

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.

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.

FTP connection and copying file using Javascript

I am new to javascript and am trying to write a script which can copy a photoshop file from the local drive to a FTP server. The file is opened in photoshop and the script is run inside it.
I followed documentation(pdf) on page 165.
var file_path = app.activeDocument.fullName
var file = new file ("/d/project/test_file.psd");
var ftp = new FtpConnection("ftp://192.168.1.150/DATA/") ;
ftp.login("username", "password");
ftp.cd("project")
ftp.put(file,"test_file.psd") ;
ftp.close() ;
file.close() ;
I get an error as the following:
Error 22: file does not have a constructor.
Line: 2
-> var file = new file("/d/project/test_file.psd");
I am not able to understand the issue properly.
Assuming you are already loading the Web Access library (webaccesslib) as stated in previous pages of your documentation, please ensure you're respecting capitalization when calling class instances.
var file = new File("/d/project/test_file.psd");
Must have File with capital F. The error is saying there's no implementation of class file.

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 Shell Script on Replica Set

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")

Node js / MongoDB replica set array in javascript

Warning: I'm a novice programmer (more of sysadmin). We were given an node js application that's using MongoDB. From what I can tell, the mongo.js file is using mongojs and monq java classes. It was setup with only one MongoDB and I'm trying to setup a new HA environment to use a replica set. Here is what they provided:
var mongojs = require('mongojs');
var monq = require('monq');
var dbName = 'exampledb';
var db = mongojs(dbName, ['collections']);
var client = monq('mongodb://127.0.0.1/exampledb', { w: 1 });
exports.db = db;
exports.ObjectId = mongojs.ObjectId;
exports.monqClient = client;
Now for a replica set, according to this article, I need to make the following change:
var db = mongojs('replset0.com, replset1.com, replset2.com/mydb?slaveOK=true?', ['collections']);
I'm not entirely sure what I need to do for the line after that. I'm guessing I would have to create an array that would contain the host name and port # for each member of the replica set (setup is primary, secondary, arbiter) such as:
var replSet = new replSet();
var replSet[0] = "server0:port0"
var replSet[1] = "server1.:port1"
var replSet[2] = "server2.:port2"
How would I go about detecting which node is the primary? Also if the primary were to fail, I would have to restart the node js application (using forever)?
I found the answer as it's calling MongoDB's URI
http://docs.mongodb.org/manual/reference/connection-string/
Should be something like:
var client = monq('mongodb://server0:port0,server1:port1,server2:port2/[dbname]?replicaSet=[replicaSet Name]
First question: As long as you give it all of the members in the connection string, the mongojs driver should be able to figure out which one is primary. No need to figure it out yourself.
Second question: No, you don't have to restart the node app. The other members in the set will elect a new primary, although it takes time for mongo to detect failure and run the election.
For more information, see the mongodb docs on replica sets.

Categories

Resources