How to use a monger connection globally in the server?

107 Views Asked by At

I have a mongodb database that I've connected to like so:

(let [uri  (config-keys :mongoURI)
      {:keys [conn db]} (mg/connect-via-uri uri)])

In Node.js with mongoose, one can do mongoose.Promise = global.Promise, to connect to the database only once and then use it from any of the files in the global namespace. How do I do this with monger so that I don't have to repeat the code above in each file that uses the database and instead connect with it only once?

1

There are 1 best solutions below

3
slipset On

So your question could be generalized to: How do I manage global state in my application.

There are several libs which help you do this:

  1. component which lets you create a map of global state which you pass to the functions that need them
  2. mount which lets you create something akin to global variables
  3. integrant

You can also do this without any specific libs, using middleware (assuming you're using ring):

(defn add-db-to-req [handler uri]
  (fn [req]
    (let [connection (mg/connect-via-uri uri)]
      (handler (assoc req :connection connection)))))

Any middleware downstream from this can access the connection by

(:connection req)

and pass it along to the functions which need it.

In general, instead of depending on global state, you will want to pass the connection along to any function that depends on it as such:

(defn fetch-from-database [{:keys [db conn] :as connection} whatever]
  ...)