I am developing an application using OpenCPU and R, I am totally new to both. I am using mongolite package to connect to MongoDB. There are multiple calls to the DB and connecting every time, takes really long. Plus data processing, plotting etc. takes quite a lot of time to load the page with the generated plot. In many cases, I have to plot fetching data from multiple collections.
I noticed that i am able to save 3-4 seconds (per connection) if I don't connect to DB each and every time, rather use an existing connection.
Will be great if anyone can guide me with the best way to check if connection is already established to the DB.
Let me brief you on what I have done so far!
Here is my connect_to_db.R file
library(mongolite)
dbConnection <- NULL
connect_mongodb = function() {
db={
if(is.null(dbConnection)){ # connect to DB only if connection is NULL, else return global connection object
m <- mongo(collection = myCollection, db = myDb, url = myUrl)
assign("dbConnection", m, envir = .GlobalEnv)
}
return(dbConnection)
}
}
It serves the purpose on sourcing the file and running it from R console. But, when I use it in my opencpu server, I make a call to connect_mongodb method from another R method that I use for plotting. I call the plotting method from a javascript file as follows.
var req = $("#plot").rplot(myPlottingMethod, options).fail(function(){
alert("Error loading results");
})
This way, my variable "dbConnection" is unknown to the method.
I tried few other ways of using <<- which i read isn't a good way to do it. Also I tried using exists() in place of is_null.
I tried another option of calling my connect_mongodb method from my javascript file using ocpu.rpc call with an idea of passing it as an argument to the R methods in rplot calls.
var req = ocpu.rpc("connect_mongodb", {})
Since connecting to mongolite doesnt return a JSON object, this attempt also failed with the below error Failed to get JSON response for http://localhost:xxxx/ocpu/tmp/x07c82b16bb/ sadly, toJSON of jsonlite and rjson did not help in converting the db object to JSON
mongolite
object if a connection exits, would testing whether amongolite
object exists work for you:all(sapply(c("mongo","jeroen"), function(x) inherits(dbConnection, x)))
? – Aldo