diff --git a/src/monger/util.clj b/src/monger/util.clj index 2947b01..698251e 100644 --- a/src/monger/util.clj +++ b/src/monger/util.clj @@ -8,7 +8,7 @@ ;; You must not remove this notice, or any other, from this software. (ns monger.util - (:import (java.security SecureRandom) (java.math BigInteger) (org.bson.types ObjectId) (com.mongodb DBObject))) + (:import (java.security SecureRandom) (java.math BigInteger) (org.bson.types ObjectId) (com.mongodb DBObject) (clojure.lang IPersistentMap) (java.util Map))) ;; ;; API @@ -36,11 +36,16 @@ `(binding [*ns* (the-ns ~ns)] ~@(map (fn [form] `(eval '~form)) body))) -(defprotocol GetDBObjectId - (get-id [input] "Returns object id")) +(defprotocol GetDocumentId + (get-id [input] "Returns document id")) -(extend-protocol GetDBObjectId +(extend-protocol GetDocumentId DBObject (get-id [^DBObject object] - (.get ^DBObject object "_id"))) \ No newline at end of file + (.get object "_id")) + + IPersistentMap + (get-id + [^IPersistentMap object] + (or (:_id object) ("_id" object)))) diff --git a/test/monger/test/util.clj b/test/monger/test/util.clj index a925041..4e3e0d2 100644 --- a/test/monger/test/util.clj +++ b/test/monger/test/util.clj @@ -5,9 +5,10 @@ (deftest get-object-id - (let [id ^ObjectId (monger.util/object-id) - input ^DBObject (monger.conversion/to-db-object { :_id id }) - output (monger.util/get-id input)] - (is (not (nil? output))))) + (let [clj-map { :_id (monger.util/object-id) } + db-object ^DBObject (monger.conversion/to-db-object clj-map) + _id (:_id clj-map)] + (is (= _id (monger.util/get-id clj-map))) + (is (= _id (monger.util/get-id db-object)))))