1

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.

Emil Ahlbäck
  • 6,085
  • 8
  • 39
  • 54
  • `(mg/connect!)` connection is available across your app – Ankur Jul 31 '12 at 10:05
  • @Ankur Yes, but I'd hate to have to connect and select the database over and over again, even if it's just two lines of code. When moving out of development is makes it even more "painful." – Emil Ahlbäck Jul 31 '12 at 10:17
  • Why do you need a connection in each model for a start? You might do this once in a separate step...? – Rom1 Jul 31 '12 at 12:22
  • @Rom1 Yes, that's what I want to do, but I seem to be doing something wrong as I have to connect! and set-db! in each "model". – Emil Ahlbäck Aug 01 '12 at 05:03

1 Answers1

2

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))).....
jassinm
  • 7,323
  • 3
  • 33
  • 42
  • Thanks, this what I thought I had done but apparently missed to require the models.clj file I used to set that connection up. Thanks for giving me assurance that this worked and letting me find the error. :) – Emil Ahlbäck Aug 01 '12 at 05:05