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?
When using monger, do I need to supply connection each request?
642 Views Asked by Levi Campbell At
2
There are 2 best solutions below
0

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.
If you work with single database then it's best to set the connection once:
But it's not a good idea when you have multiple databases. Monger have
with-connection
macro (see API docs) for this case:You may establish all connections once during the initialization of your app:
and then use them:
Update. In our application we have a hash-map of all database connections:
mongo-config
variable stores specification for all our databases andwith-db
macro makes it easy to access them by their names: