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.
Related
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.
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.
I have application store and applications have their url. I want to download apks from those urls to my jaggery server. Although below code(my first solution) create myApp.apk successfully, its not work properly.
First i tried to below code,
var url = "http://img.xxx.com/006/someApp.apk";
var data = get(url, {});
var file = new File("myApp.apk");
file.open("w");
file.write(data.data);
file.close();
when i print data.data value, its look like
i also tried,
var file = new File("http://img.xxx.com/006/someApp.apk");
file.saveAs("myApp.txt");
Can anyone help me?
.apk files are Android application files, and they are expected to start with PK, because they are actually zip archives!
They're not meant to be unzipped, although you can do it to see some of the application resources (but there are better ways for reverse engineering .apk files such as Apktool, if that's what you're looking for).
According to jaggery documentations, file.write is writing the String representation of the object to the file. So that's why you are getting an apk file which cannot be installed.
However you can make it work using copyURLToFile in apache commons-io java library as follows since jaggery supports java itself and all of WSO2 products have apache commons-io library in their class path.
<%
var JFileUtils = Packages.org.apache.commons.io.FileUtils;
var JUrl = Packages.java.net.URL;
var JFile = Packages.java.io.File;
var url = new JUrl("http://img.xxx.com/006/someApp.apk");
JFileUtils.copyURLToFile(url, new JFile("myApp.apk"));
print("done");
%>
Your file will be stored on $CARBON_HOME directory by default, unless you specified relative or absolute path to the file.
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.
I'm new to JavaScript and creating classes/objects. I'm trying to wrap an open source library's code with some simple methods for me to use in my routes.
I have the below code that is straight from the source (sjwalter's Github repo; thanks Stephen for the library!).
I'm trying to export a file/module to my main app/server.js file with something like this:
var twilio = require('nameOfMyTwilioLibraryModule');
or whatever it is I need to do.
I'm looking to create methods like twilio.send(number, message)that I can easily use in my routes to keep my code modular. I've tried a handful of different ways but couldn't get anything to work. This might not be a great question because you need to know how the library works (and Twilio too). The var phone = client.getPhoneNumber(creds.outgoing); line makes sure that my outgoing number is a registered/paid for number.
Here's the full example that I'm trying to wrap with my own methods:
var TwilioClient = require('twilio').Client,
Twiml = require('twilio').Twiml,
creds = require('./twilio_creds').Credentials,
client = new TwilioClient(creds.sid, creds.authToken, creds.hostname),
// Our numbers list. Add more numbers here and they'll get the message
numbers = ['+numbersToSendTo'],
message = '',
numSent = 0;
var phone = client.getPhoneNumber(creds.outgoing);
phone.setup(function() {
for(var i = 0; i < numbers.length; i++) {
phone.sendSms(numbers[i], message, null, function(sms) {
sms.on('processed', function(reqParams, response) {
console.log('Message processed, request params follow');
console.log(reqParams);
numSent += 1;
if(numSent == numToSend) {
process.exit(0);
}
});
});
}
});`
Simply add the function(s) you wish to expose as properties on the exports object. Assuming your file was named mytwilio.js and stored under app/ and looks like,
app/mytwilio.js
var twilio = require('twilio');
var TwilioClient = twilio.Client;
var Twiml = twilio.Twiml;
var creds = require('./twilio_creds').Credentials;
var client = new TwilioClient(creds.sid, creds.authToken, creds.hostname);
// keeps track of whether the phone object
// has been populated or not.
var initialized = false;
var phone = client.getPhoneNumber(creds.outgoing);
phone.setup(function() {
// phone object has been populated
initialized = true;
});
exports.send = function(number, message, callback) {
// ignore request and throw if not initialized
if (!initialized) {
throw new Error("Patience! We are init'ing");
}
// otherwise process request and send SMS
phone.sendSms(number, message, null, function(sms) {
sms.on('processed', callback);
});
};
This file is mostly identical to what you already have with one crucial difference. It remembers whether the phone object has been initialized or not. If it hasn't been initialized, it simply throws an error if send is called. Otherwise it proceeds with sending the SMS. You could get fancier and create a queue that stores all messages to be sent until the object is initialized, and then sends em' all out later.
This is just a lazy approach to get you started. To use the function(s) exported by the above wrapper, simply include it the other js file(s). The send function captures everything it needs (initialized and phone variables) in a closure, so you don't have to worry about exporting every single dependency. Here's an example of a file that makes use of the above.
app/mytwilio-test.js
var twilio = require("./mytwilio");
twilio.send("+123456789", "Hello there!", function(reqParams, response) {
// do something absolutely crazy with the arguments
});
If you don't like to include with the full/relative path of mytwilio.js, then add it to the paths list. Read up more about the module system, and how module resolution works in Node.JS.