Introduce monger.core/connect! and monger.core/set-db!
Even though it is not idiomatic Clojure to mutate vars like this, it is very common for many applications to only use one MongoDB connection (so, no per-thread var rebinding) and one main database. For those cases, these function eliminate the need for mundaine hacks with namespace switching.
This commit is contained in:
parent
a6d96da5bd
commit
5e12f9aec2
2 changed files with 14 additions and 4 deletions
|
|
@ -11,7 +11,7 @@
|
||||||
:doc "Thin idiomatic wrapper around MongoDB Java client. monger.core includes
|
:doc "Thin idiomatic wrapper around MongoDB Java client. monger.core includes
|
||||||
fundamental functions that work with connections & databases. Most of functionality
|
fundamental functions that work with connections & databases. Most of functionality
|
||||||
is in the monger.collection namespace."}
|
is in the monger.collection namespace."}
|
||||||
monger.core
|
monger.core
|
||||||
(:refer-clojure :exclude [count])
|
(:refer-clojure :exclude [count])
|
||||||
(:use [monger.conversion])
|
(:use [monger.conversion])
|
||||||
(:import (com.mongodb Mongo DB WriteConcern DBObject DBCursor)
|
(:import (com.mongodb Mongo DB WriteConcern DBObject DBCursor)
|
||||||
|
|
@ -48,6 +48,7 @@
|
||||||
([{ :keys [host port] :or { host *mongodb-host*, port *mongodb-port* }}]
|
([{ :keys [host port] :or { host *mongodb-host*, port *mongodb-port* }}]
|
||||||
(Mongo. ^String host ^Long port)))
|
(Mongo. ^String host ^Long port)))
|
||||||
|
|
||||||
|
|
||||||
(defn ^DB get-db
|
(defn ^DB get-db
|
||||||
"Get database reference by name.
|
"Get database reference by name.
|
||||||
|
|
||||||
|
|
@ -61,6 +62,16 @@
|
||||||
(.getDB connection name)))
|
(.getDB connection name)))
|
||||||
|
|
||||||
|
|
||||||
|
(defn connect!
|
||||||
|
^Mongo [& args]
|
||||||
|
(def ^:dynamic *mongodb-connection* (apply connect args)))
|
||||||
|
|
||||||
|
|
||||||
|
(defn set-db!
|
||||||
|
[db]
|
||||||
|
(def ^:dynamic *mongodb-database* db))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
(defprotocol Countable
|
(defprotocol Countable
|
||||||
(count [this] "Returns size of the object"))
|
(count [this] "Returns size of the object"))
|
||||||
|
|
|
||||||
|
|
@ -4,9 +4,8 @@
|
||||||
(:use [clojure.test]))
|
(:use [clojure.test]))
|
||||||
|
|
||||||
|
|
||||||
(monger.util/with-ns 'monger.core
|
(monger.core/connect!)
|
||||||
(defonce ^:dynamic *mongodb-connection* (monger.core/connect))
|
(monger.core/set-db! (monger.core/get-db "monger-test"))
|
||||||
(defonce ^:dynamic *mongodb-database* (monger.core/get-db "monger-test")))
|
|
||||||
|
|
||||||
|
|
||||||
(deftest connect-to-mongo-with-default-host-and-port
|
(deftest connect-to-mongo-with-default-host-and-port
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue