Keeping a global monger connection accessible from all models

677 Views Asked by At

Being new at both Clojure, Noir and Monger I'm facing just a small issue. As seems standard in Noir I keep my models in src/app_name/model_name.clj

The problem I'm facing is that I need to make the same connection to MongoDB in each model, as I don't know how to properly "share" the connection, like so:

(ns app.models.theme
 (:require [monger.collection :as mc]
            [monger.core :as mg]))

(mg/connect!)
(mg/set-db! (mg/get-db "app_development"))

; Do stuff

How would I go about sharing this connection through the entire app? Thank you.

1

There are 1 best solutions below

1
On BEST ANSWER

if you always connect to the same server then just add this in your server.clj (src//server.clj)

(mg/connect!)

If you only use one db within that server you just add :

(mg/set-db! (mg/get-db "dbname"))

to the same file

otherwise you can do for example on an entry point or anywhere in the code

(defpage "/dbname/tothis" {:keys [dbname]}

  (mg/with-db (mg-get-db dbname))).....