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:
Michael S. Klishin 2011-09-19 12:14:48 +04:00
parent a6d96da5bd
commit 5e12f9aec2
2 changed files with 14 additions and 4 deletions

View file

@ -11,7 +11,7 @@
:doc "Thin idiomatic wrapper around MongoDB Java client. monger.core includes
fundamental functions that work with connections & databases. Most of functionality
is in the monger.collection namespace."}
monger.core
monger.core
(:refer-clojure :exclude [count])
(:use [monger.conversion])
(:import (com.mongodb Mongo DB WriteConcern DBObject DBCursor)
@ -48,6 +48,7 @@
([{ :keys [host port] :or { host *mongodb-host*, port *mongodb-port* }}]
(Mongo. ^String host ^Long port)))
(defn ^DB get-db
"Get database reference by name.
@ -61,6 +62,16 @@
(.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
(count [this] "Returns size of the object"))

View file

@ -4,9 +4,8 @@
(:use [clojure.test]))
(monger.util/with-ns 'monger.core
(defonce ^:dynamic *mongodb-connection* (monger.core/connect))
(defonce ^:dynamic *mongodb-database* (monger.core/get-db "monger-test")))
(monger.core/connect!)
(monger.core/set-db! (monger.core/get-db "monger-test"))
(deftest connect-to-mongo-with-default-host-and-port