title: mongolite best practices
body: <p>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. </p>
  
  <p>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. </p>
  
  <p>Will be great if anyone can guide me with the best way to check if connection is already established to the DB. </p>
  
  <p>Let me brief you on what I have done so far!</p>
  
  <p>Here is my connect_to_db.R file</p>
  
  <pre><code>library(mongolite)
  
  dbConnection &lt;- NULL
  
  connect_mongodb = function() {
  db={
        if(is.null(dbConnection)){  # connect to DB only if connection is NULL, else return global connection object
          m &lt;- mongo(collection = myCollection, db = myDb, url = myUrl)
          assign("dbConnection", m, envir = .GlobalEnv)
        }
        return(dbConnection)
      }
  }
  </code></pre>
  
  <p>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.</p>
  
  <pre><code>var req = $("#plot").rplot(myPlottingMethod, options).fail(function(){
      alert("Error loading results");
  })
  </code></pre>
  
  <p>This way, my variable "dbConnection" is unknown to the method. </p>
  
  <p>I tried few other ways of using &lt;&lt;- which i read isn't a good way to do it. Also I tried using exists() in place of is_null. </p>
  
  <p>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.</p>
  
  <pre><code>var req = ocpu.rpc("connect_mongodb", {})
  </code></pre>
  
  <p>Since connecting to mongolite doesnt return a JSON object, this attempt also failed with the below error
  <strong>Failed to get JSON response for <a href="http://localhost:xxxx/ocpu/tmp/x07c82b16bb/" rel="noreferrer">http://localhost:xxxx/ocpu/tmp/x07c82b16bb/</a></strong>
  sadly, toJSON of jsonlite and rjson did not help in converting the db object to JSON</p>