We need someplace to store our data, and so the first thing our project will need is persistence.
I used MongoDB and monger
lib for it. There are 2 options that you can use
- local db or
- remote service like MongoHQ
MongoHQ provides a free “Sandbox” plan with ( 512mb). As i planed to host my app at heroku i choosed to use remote db from the start. Moreover MongoHQ has nice interface to manage your dbs, collections and records. Here is setup steps to use mongohq account.
Create account at MongoHQ.
Create DB at mongohq.
Collection is created when you first time create a record.
Place [com.novemberain/monger “1.3.1”] to your project.clj file in :dependencies section.
This will install monger lib.
Ok let’s make some edits to our server.clj file. We will use mongodb uri:
Usually you need 2 dbs one for development and one for production ( if you test your app then also test db). I am using 2 dbs dev and prod. To use dev db i pass dev param to -main function via lein run.
lein run dev
Final code will be something like this:
There is :dev mode option in noir.server but i had no time to investigate how that can be used to switch dev and prod modes and how to use dev db in dev mode and prod db in prodaction mode.
Simple web app “Bookshelf”
Ok suppose we have some books on the shelf and want to create a list of that books and maybe add some other info later for example when book was read, what that book about and so on. Of course our book has Title and Author.
For making html i will use Hiccup lib. There are other libs for that for example Enlive but Hiccup is my favourite for now.
Let’s add simple form with author and title fields and create post action that will send our data to dev db.
Here is our form, note that we need to add to (:use [hiccup.form]):
Next we implement post action that will send our data to db. Notice that to use our monger lib we should add [monger.collection :as monger] to :require and to make redirect we will add
[noir.response :as response]
Next we will render our list of books above our form. We will do this in 2 steps:
- first we bind our template with data with map
- make our template that will acquire data:
Finally all our code will look something like this:
Refresh the page and you will see our app.
For better ui i added bootstrap css to common.clj and added container class dev.container.
We learned how to add support for MongoDB with Monger lib and how to use remote DB provider.
Short algoritm of work of our app
- enter data to ther form ( title and author)
- send that data to db via post action
- in post action use moger/insert to insert date to db
- after that redirect to main page with response/redirect
- list our data with books-list partial ( which consist of template and data) at main page
All code will live in github repo so that you can clone it and try it for yourself.
Next we will add support for image uploading via filepicker service.