Search code examples
mongodbdockerclojurecompojure

I'm attempting to connect to MongoDB with a Clojure application, via Docker


I have the following docker-compose rules...

catalog-service:
    build: ./services/catalog 
    ports: 
        - "2000:3000"
    depends_on:
        - catalog-datastore
    restart: always

catalog-datastore:
    image: mongo:3.0
    command: mongod --smallfiles --quiet --logpath=/dev/null
    ports: 
        - "27017:27017"

The following Dockerfile for the clojure app...

FROM clojure
COPY . /usr/src/app
WORKDIR /usr/src/app
CMD ["lein", "ring", "server"]

And the following connection code in my app...

(ns catalog.handler
  (:import com.mchange.v2.c3p0.ComboPooledDataSource)
  (:use compojure.core)
  (:use cheshire.core)
  (:use ring.util.response)
  (:require [compojure.handler :as handler]
            [ring.middleware.json :as middleware]
            [clojure.java.jdbc :as sql]
            [compojure.route :as route]
            [somnium.congomongo :as m]))

(def conn
  (m/make-connection "catalog"
                     :host "catalog-datastore"
                     :port 27017))

(defn get-all []
  (m/fetch :catalog))

(defn get-single [id]
  (m/fetch-one
    :catalog
    :where{:_id (Long/parseLong id)}))

(defroutes app-routes
  (context "/catalog" [] (defroutes catalog-routes
                           (GET "/" [] (get-all))
                           (GET "/:id", [id] (get-single)))))

(def app 
  (-> (handler/api app-routes)
      (middleware/wrap-json-body)
      (middleware/wrap-json-response)))

When I try to run the app I get the error...

java.lang.AssertionError
Assert failed: (connection? conn)

Solution

  • From the docs:

    set the connection globally
    
    (m/set-connection! conn)
    
    or locally
    
    (m/with-mongo conn
      (m/insert! :robots {:name "robby"}))
    

    Looks like you missed that bit. :p