Clojure-避免monger请求中的重复代码

Clojure-避免monger请求中的重复代码,clojure,monger,Clojure,Monger,我正在使用Clojure和 它工作得很好,我根据函数相关的集合对函数进行分组。 因此,每个文件都是这样开始的: (ns img-cli.model.mycollectionname (:require [monger.core :as mg] [monger.collection :as mc] [edn-config.core :refer [env]]) (:import [com.mon

我正在使用Clojure和

它工作得很好,我根据函数相关的集合对函数进行分组。 因此,每个文件都是这样开始的:

(ns img-cli.model.mycollectionname
  (:require [monger.core            :as mg]
            [monger.collection      :as mc]
            [edn-config.core        :refer [env]])
  (:import  [com.mongodb MongoOptions ServerAddress DB WriteConcern]
            [org.bson.types ObjectId]))


(def config (get-in env [:mongo]))

;; using MongoOptions allows fine-tuning connection parameters,
;; like automatic reconnection (highly recommended for production
;; environment)
(def ^MongoOptions  opts (mg/mongo-options { :threads-allowed-to-block-for-connection-multiplier 300}))
(def ^ServerAddress sa   (mg/server-address (:url config) (:port config)))
(def conn                (mg/connect sa opts))
(def db                  (mg/get-db conn (:db config)))

(def collection-name "asset")

;; I have to write one like this every time
(defn find-one-as-map
  "fetch asset by Id"
  [^String id]
  (mc/find-one-as-map db collection-name {:_id (ObjectId. id)}))
代码复制本身当然有几个缺点。 另外,我不确定之后是否正确地汇集了连接

我怎样才能避免这样做? 我感觉我可以给每个函数传递一个额外的db参数,但是它从哪里来呢

如果我在程序的入口文件中创建db连接,那么如何将其传递给每个函数呢

例如,假设我在不同的文件中有Compojure路由:

;; in the main handler file

(def db ...) ;; if I move the previous db configuration
             ;; in here, it could be the only place where this is set

;; importing Compojure routes from different files
(defroutes routes-from-file1
                  routes-from-file2...)
假设从file2中的某些路由调用的某些函数需要访问db,如何将此变量传递给它们

之后我还有很多重复的代码,例如通过Id获取每个集合的数据。。。
我觉得这可以简化,但我不确定如何简化。

只需通过名称空间引用它即可

(ns foo
  (:require [handler :as h]))
(println h/db)