When using monger, do I need to supply connection each request?

642 Views Asked by At

In the documentation, the mongodb connection is established once, before being used without passing the connection to each command, is that the proper way to use monger, or should I pass the database connection to each call?

2

There are 2 best solutions below

0
On BEST ANSWER

If you work with single database then it's best to set the connection once:

(mg/connect! db-spec)

But it's not a good idea when you have multiple databases. Monger have with-connection macro (see API docs) for this case:

(mg/with-connection db-connection
  ...)

You may establish all connections once during the initialization of your app:

(def conn1 (mg/connect db-spec))

and then use them:

(mg/with-connection conn1
  ...)

Update. In our application we have a hash-map of all database connections:

(def  ^:dynamic
      ^clojure.lang.PersistentArrayMap
      *connections*
      {})

(defn connect! [db]
  {:pre [(contains? mongo-config db)]}
  (if (-> db *connections* nil?)
      (let [conn (mg/connect (get mongo-config db))]
        (alter-var-root #'*connections*
                        assoc
                        db
                        { :conn conn
                          :db   (mg/get-db conn (name db))})))
  (-> *connections* db :conn))

(defmacro with-db [db & body]
  "Eval body using :amonplus or :statistic db"
  `(mg/with-connection (connect! ~db)
    (mg/with-db        (clojure.core/-> *connections* ~db :db)
      ~@body)))

mongo-config variable stores specification for all our databases and with-db macro makes it easy to access them by their names:

(with-db :my-db
  ...)
0
On

Now (version 2.0) is necessary for all key public API functions use an explicit DB/connection/GridFS object.

so:

(require '[monger.collection :as mc])

(mc/insert db "libraries" {:name "Monger"})

To get this work:

 (let [conn (mg/connect)
     db   (mg/get-db conn "monger-test")]
      (mc/insert db "libraries" {:name "Monger"}))

How I can use the "db" reference accross all my code.