0

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?

zengod
  • 1,114
  • 13
  • 26

1 Answers1

0

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]
  ...)
slipset
  • 2,960
  • 2
  • 21
  • 17
  • 1
    The last paragraph is the key: "In general, instead of depending on global state, you will want to pass the connection [not username and password] along to any function that depends on it". – Biped Phill Feb 04 '20 at 10:16
  • @slipset, would you please explain the last part of your answer? How do I pass in the connection if it is in another file into a function without using global states? – zengod Feb 09 '20 at 12:41
  • Something like this https://gist.github.com/slipset/c405bbb27f77eb5215eca4a365eb359a – slipset Feb 10 '20 at 07:28