kinguin

onsdag den 2. november 2016

Populate select with Handlebars, Express and Mysql

So recently I started learning JavaScript as I have fallen in love with Node Js. To me it looks like Node Js and the entire Javascript scene is here to stay. As Node Js becomes more popular and is used in more devices there will be a bigger demand for Javascript developers.

Currently, I am building a website using Handlebar, Express, and Mysql2 npm modules. In this project, I needed to load data from my database and display it in a select element in my view.
I had a hard time finding a tutorial that explained how to do this in a proper way so following various tutorials i managed to hack something together that works. And I'm almost certain that it's the right way to do it.

So let's begin, I assume that you have knowledge of Node Js and npm and how to create a new Express project.

I have a categories model that can do basic CRUD operations on my categories table in the database.
//models/categories.js

var mysql = require('mysql2')
var db = require('./db')

exports.getAllCategories = function() {
  return new Promise(function(resolve, reject) {
    var connection = db.getConnection()

    connection.query('SELECT * FROM category', 
      function(err, results, fields) {

      if (err) {
        return reject(err)
      }
      resolve(results)

    })
    connection.end()
  })
}

Then i have a controller (which resides in routes because Express thinks thats a good name).
//routes/categoryRoute

var express = require('express')
var router = express.Router()
var categories = require('../models/categories')

router.get('/category', function(req, res, next) {
  categories.getAllCategories().then(function(result) {
    res.render('category', {arr: result})
  }).catch((err) => setImmediate(() => { throw err }))
})

And lastly i have my view where i want to display the data.
    <div class="form-group">
      <label for="category" class="col-md-3 control-label">Category</label>
      <div class="col-md-9">
        <select class="form-control" name="category" id="kategori">
          {{#each arr}}
            <option value="{{this.Id}}">{{this.Name}}</option>
          {{/each}}
        </select>
      </div>
    </div>

In order to iterate through the data in the view that we got from our controller, we have to give our result array a name.
In this example i just named it arr and then we can iterate through it using handlebars {{#each}} helper.
This is quick and dirty and i hoped it helped you achive the result you hoped for.