Getting started: Weber + Mongodb

The main idea of this post is to show simple example how to build ElixirLang + Mongodb web application from scratch. First of all we must to get weber source code, build it and create new project. Get Weber with:
git clone git@github.com:0xAX/weber.git
build it with:
mix deps.get && mix compile
and create new project:
mix weber.new testMongoApp
Now go to the testMongoApp and build our new web application with:
mix deps.get && mix compile
Now we must install mongodb, here i will not tell how to do it. All instructions you can find at official mongodb web site. Let's think that you successfully compiled testMongoApp web application and have already launched mongodb. Open now your mix.exs file and add Mongoex to the deps:


Next step is to set up Mongoex at the lib/app.ex. Add there following lines to the start function:


We'll build simple web application, which will consists from 2 html pages and will be users saving and search by user name. Let's configure routing for our web application. It will be like this:


Here are 4 routes:
  • Render main page
  • Save user
  • Render search page
  • Search user age by name
So... Our web application uses mongodb database for user storing, let's create model for it in lib/model/users.ex


Here is User model with 2 fields: name and age. Now go to the Main controller. There are must be 2 actions there: index/2 and add/2. First action just renders lib/views/main/index.html template:


And second action gets user name and age from ajax request and save it to the database:


Second controller is for user search by name. It has two actions two: list and find, first action renders search page:


and second action handles user search:


As you can see at the templates source code we user jquery javascript library for DOM manipulation and sending AJAX request to the server. Here is client side code for it:


Links

Comments