Setting Up a Database Node Module on a Node/Express Server with Sequelize

If you just need to get a node server up and running with very few lines of code then you hopefully already know about Node/Express (if you don’t, the Express website has a pretty good intro tutorial and has good documentation to get started serving up static assets). If you need all of that and to be able to route queries to a database quickly and easily then you might not know about the awesome power of Sequelize.

If you haven’t messed around with a ORM (Object Relational Mapper, a program that maps your code to a database) before, Sequelize is a really straight forward one to start with.

var voteTable = sequelize.define('vote', {
  video_id: Sequelize.STRING,
  timestamp: Sequelize.INTEGER,
  vote: Sequelize.INTEGER
});

voteTable.sync();

Once I had my server set up (and installed the sequelize dependencies). This was the line of code I needed to use to create a new table for my current group project. Sequelize automatically includes extra columns like unique id and created at/updated at timestamps (there are ways to tell it not to too).

The rest of the initial set up is easy too, but it’s well documented over in the Sequelize docs. The fun part comes when you can start to make your database more modular. The first thing I did was to take out the actual username/password information from my database connection. I stored them as an object in a separate JavaScript file (so I could add it to .gitignore and not share my passwords with the world).

//module.exports allows us to use this code in other places as a node module, 
//we'll see it again when I make the database calls modular
module.exports = { 
  database: 'database_name', 
  username: 'username', 
  password: 'secret_password',
  host: 'host_url',
  port: 5432,
  dialect: 'postgres', //obviously you don't have to use PostgreSQL
  native: true //required for Heroku Postgres (I'll cover that in another post)
};

I saved that snipped to a file called db_config.js at the root directory and then created my main database module in the subfolder /controller/ called database.js. So to have access to the private config object, all I need to do is set up my dependencies, import the db_config file, and I can start using my config variables to connect to my database:

var Sequelize = require('sequelize');
var pg = require('pg').native; //again this line is specific to using a Postgres database
var config = require('../db_config');

var sequelize = new Sequelize(config.database, config.username, config.password, {
  host: config.host,
  port: config.port,
  dialect: config.dialect,
  native: config.native //Heroku Postgress again
});

Now between that code and my creating a table I have full access to a database, but now I need to get this all into my main app.js simple server I created with Node/Express. This is a super easy leap. First I create my functions to send and retrieve data in /controller/database.js:


module.exports.createVote = function(req, res){
  //code to bundle up the created object and save it do the database
};

module.exports.getVotes = function(req, res){
  //code to find votes based on specific requests from the user
};

Now to have access to these functions (which are a part of the database.js node module, thanks to the module.exports object which is a feature of Node) I only need to require database.js in my main server app and call the functions where I need them:

var database = require('./controllers/database');

//many lines later
app.post('/votes', database.createVote);
app.get('/votes/:vidID', database.getVotes);

The /votes/:vidID is a handy trick of Express to pass information to the server. The value gets attached to the req.param.vidID property so I can use it when I request specific information from the server. For example if I wanted to query for results from a video ID of 123 I would send a post request to /votes/123 and then my req.param.vidID === 123.

One last trick, in Sequelize when you query the database you get back quite a few more rows than you might expect. When I query my voteTable (the one I only explicitly created three columns for?) I get back something that looks like this monster:

 { dataValues: 
     { video_id: '7QBgK0_RbkE', timestamp: 2, vote: 1, id: 192,
       createdAt: Sun Dec 22 2013 22:19:33 GMT-0800 (PST),
       updatedAt: Sun Dec 22 2013 22:19:33 GMT-0800 (PST) },
    __options: 
     { timestamps: true, createdAt: 'createdAt', updatedAt: 'updatedAt',
       deletedAt: 'deletedAt', touchedAt: 'touchedAt', instanceMethods: {}, classMethods: {}, 
       validate: {}, freezeTableName: false, underscored: false, syncOnAssociation: true,
       paranoid: false, whereCollection: [Object], schema: null, schemaDelimiter: '',
       language: 'en', defaultScope: null, scopes: null, hooks: [Object], omitNull: false, 
       hasPrimaryKeys: false },
    hasPrimaryKeys: false,
    selectedValues: 
     { video_id: '7QBgK0_RbkE', timestamp: 2, vote: 1, id: 192,
       createdAt: Sun Dec 22 2013 22:19:33 GMT-0800 (PST),
       updatedAt: Sun Dec 22 2013 22:19:33 GMT-0800 (PST) },
    __eagerlyLoadedAssociations: [],
    isDirty: false,
    isNewRecord: false,
    daoFactoryName: 'votes',
    daoFactory: 
     { options: [Object], name: 'votes', tableName: 'votes', rawAttributes: [Object],
       daoFactoryManager: [Object], associations: {}, scopeObj: {}, primaryKeys: {},
       primaryKeyCount: 0, hasPrimaryKeys: false, autoIncrementField: 'id', DAO: [Object] } 
 } 

And that’s just ONE entry in the database! To fix that add an option to your sequelize query: {raw: true} so the query would look like:

voteTable.findAll(query, {raw: true})

And one entry of output would be:

{ video_id: 'T-D1KVIuvjA',
    timestamp: 2,
    vote: 1,
    id: 1,
    createdAt: Sat Dec 21 2013 14:55:42 GMT-0800 (PST),
    updatedAt: Sat Dec 21 2013 14:55:42 GMT-0800 (PST) }

That is enough database tricks for today. If you want to just stare at my code for a while to create & retrieve votes from our database you can find my gist here (with sanitized login info for the db_config). The real (still being modded by the team) code is forked on my GitHub. I have a few more of these in the works from my adventures slinging code and I hope to post a few more before Hack Reactor starts back up and I lose all free time again.

Week 6: Whole New Ballgame

The tiny bit of Hack Reactor/git humor above is going to be lost on most of my audience but it made me happy. This week felt a bit like the first week of the program. A bit of uncertainty, a lot of excitement.

We were turned loose this week. No more structured lessons, it’s the start of the projects phase. The first two days were devoted to a “hackathon” where I learned angular and firebase and created a bookmarking app that included full-text search and a companion Chrome extension. That was super exciting. It was awesome to build something with my own two hands and realize all that I’ve learned in the past six weeks. Even if something didn’t work right off the bat, I now have the confidence to read through the documentation and understand what individual pieces weren’t functioning the way I expected them to. One of my best strengths has definitely been my super-human ability to craft a google search query.

The rest of the week has been a move into group projects and learning a whole new skill-set. I’m a get-along kind of person by nature and it was hard at first for me to feel like I wasn’t stepping on toes when I wanted to work on a specific part of our project. After a day or so of planning and modeling what we wanted to do though, it became easier to split up tasks. I learned Asana (a project tracking app) and got really good at dividing up tasks.

My favorite part of our new app is that I got to deep dive into d3 (a JavaScript library for data visualizations) functionality and create a homegrown heat-map. Some of my notes are up on GitHub, but I plan on refactoring and creating a whole post on the heat-map process (spoiler: d3.rollup is my savior).

I am very content this week. I’m getting a taste of what the real world is going to look like for me as a software engineer (an unfortunate side effect is that I’m getting a real taste for coffee to keep up with the long Hack Reactor hours). Now though, I’m sitting in SFO waiting for my plane to PDX and home for Christmas. I’ll miss the beautiful (and non-rainy) sites of San Francisco, but I’m excited to visit family and show them how much I’ve changed.

Week 4: Losing Power

Another roller coaster week. Worst points: Someone took my laptop charger while I was in lecture, my week 3 assessment was not my finest point, and I miss my cats something desperately. Best points: I worked with my two favorite pair-partners again because I couldn’t handle this week otherwise, I had an awesome girl’s lunch today with 4/5ths of the junior class women (there are 5 of us total), and I made a node.js server!

So I definitely felt my first crazy/not enough sleep/irrational emotions. When my power cord was jacked a couple of days ago I was devastated. In retrospect, I think I’m a little tired and cranky and, like I said previously, I am in desperate need of some kitty cuddle time. I’ve  been in California now for over a month and I still love it, but it’s definitely getting more difficult. There are times I wish I could just zen out and I only really get that on the trains or at midnight in the dark when I should be sleeping so I can wake up and do it all again the next morning at 6am to catch my train.

I have never been more excited/motivated to get up in the morning in my life and I can’t get to sleep at night because code and other things are running through my head and along the way something had to give. I’ve discovered that when something has to give it’s my emotional stability. My actual sprints were amazeballs, especially since I had awesome pairs (Sara and Andy, respectively) for my Backbone and Node.js sprints. But in my quiet moments or while I was working solo the doubt and sadness came back.

So I did what I always do when I’m sad – I talked to my parents, a lot. I called them while waiting for the train, I called them sitting on the couch in the Hack Reactor lobby during lunch, and I called them while I drove home at 9pm every night. My dad especially is awesome at making me feel better. He’s always so proud of me and he’s always  interested in what I’m doing. It’s hard sometimes here, but I have an amazing support system both in Oregon and here. My platonic life partner Ava and her husband John have been my rocks in more ways than one. My new awesome friends at Hack Reactor, especially the ladies of the Nov ’13 cohort have been awesome to get to know. And I know all my family, friend, and former coworkers back in Oregon love me and miss me as much or more than I love and miss them.

Thinking about it and even writing about it has helped as well. Getting it off my chest makes it so I can breathe again. So I guess I just want to say, I love you all. Thank you for dealing with me! I really am happy even if I didn’t sound it sometimes this week. If I don’t just sleep all of tomorrow/spend my day in San Jose with other awesome people I love to pieces, I’m going to try to post a non-emotional/tired/whiny post, but honestly, I want to keep this blog real. For me as well as for you and this what has dominated my brain this week.

Inside My Head: Learning JavaScript

I have had a very productive weekend so far (and it’s only Saturday!). I am spending some of my day today going back through my easy Coderbyte solutions and cleaning most of them up. I will also be adding in comments for most of the lines explaining my logic. So a lot of the files will look like this:

 function FirstReverse(str) { 
   return str.split("")  //splits the string into an array of characters 
             .reverse()  //reverses the array 
             .join("");  //joins the array back into a string, with no space between the characters 
 } 

This is actually a lot of fun for me. Now that we’re getting into more abstract concepts like MVCs and servers it’s nice to just go back and power through some JavaScript code and understand exactly what it’s doing.

As always, you can find my coderbyte solutions on GitHub (I will be posting updates to it throughout the day), but I feel like I need to start adding a caveat, because of the amount of people who have said they found my blog looking for coderbyte solutions. Just staring at my code isn’t going to make you understand JavaScript. You need to do it for yourself. If you’re brand new to JavaScript, just seeing the cool tricks is not going to make you a programmer. I really recommend things like Udacity, Codecademy and other sites that talk about the fundamentals of comp sci/programming.

Week 3 – Less Work, More… Work?

School-wise, this week was very, very short. Today is Thanksgiving and I’m almost a little shocked that we got it off (although many of my peers are spending their day at the school if the emails about keys and door opening flying back and forth are a good reference). Because of the shortness I was thrown a bit off guard on Monday when I realized that it was time for our 3rd assessment already! This is week three! It feels simultaneously like I’ve been here for days and for years. The assessment went well and I actually remembered all my things from the previous week without too much panic. I did have a hilarious nightmare afterward that involved me being forced to code a merge sort algorithm using a pencil and a very limited amount of paper and my lead instructor yelling at me for my terrible handwriting (this is why I love computers! I have terrible penmanship).

Because of the short week we basically just went straight into Backbone.js this week, which for my non-coding followers is a JavaScript library that allows you to structure your app cleanly by dividing the work that must be done into the actual data “models” and the way you represent that data to individuals “views”. This concept is what’s called an MVC, which is one of those trendy/useful buzzwords you hear a lot in coding. Anyway, it’s what we did in class this week and I plan on working on it a bunch over my long weekend.

Unfortunately because this is the longest break I have besides solo project time during Christmas break I think I’ve put more on my to-do list than is physically possible (especially since I promised my platonic life partner Ava I would help her with her Hackbright project too). Lets run down what I have on my list:

  • Review algorithm time complexity (Big O notation)
  • Practice recursive problems
  • Make business cards:
    Personal business cards of awesome
  • Work on my Backbone project (we are working on it through next Tuesday, but I want to tackle some of the extra credit)
  • Redo/refactor some of my Coderbytes code – I’ve learned a bunch, I can probably do better
  • Research getting involved in some open source stuff/get some pull requests in to bigger projects
  • Maybe try learning Ruby on Rails (we might lose out on the Ruby on Rails sprint because of the timeline of holidays)

So yeah, I’m probably a crazy person. Today I will eat and hang out with friends and be merry though. Tonight I will allow the code to creep its way to the front of my brain again. I also plan on writing a more technical article on time complexity sometime this weekend if I can wrap my brain more fully around it so I can pass along the tips I find.

Week 2 – Programmers Do It Algorithmically

I have less pretty pictures for you this week. The most I saw of the sunshine looked similar to this:

View from the 8th floor

At least it was sunshine. It “rained” for like a minute one day and the umbrellas came out en masse. I was perfectly happy in a hoodie, but I definitely felt like an outsider. I might need to buy an umbrella, this whole trying to not look like a tourist thing is harder than I thought. Although I’ve had more people ask me for directions this week than I ever have in my life combined so I think the hair and the nose piercing are good SF camouflage.

This week was a teensy bit rollercoastery for me. We started out with a fairly easy CSS/fun jQuery tricks problem and then tackled a pretty epic sprint on the N-Queens problem. N-queens is the idea that you need to place n (a number) of chess queens on an nxn chess board so that none of the queens can attack any other queen. I think they’ve only solved it up to 27 ( and that was people from Hack Reactor). I got a little flustered with that one as algorithms were never my strong suit before this (it’s why I got the “conditionally acceptance” at App Academy – thank god, might I add). I think though I’m just being too hard on myself. Not every software engineer deals with something as crazy as the n-queens problem on an everyday basis. Our more traditional daily toy problems (similar to tech interview questions) are fairly straight forward and I can code a bubble sort algorithm in about 5 minutes (maybe 10 with one hand tied behind my back).

I think that’s what Hack Reactor has done for me more than anything else. It’s made me accept my flaws, but know that everyone has them and there is always more to learn. I’m a good intuitive coder, but I’m no good with the lingo of it. We all are here to learn to become great coders Software Engineers.

Short post this week, sorry. I have dinner with friends to go to and my Sunday is too peaceful and sunny (and full of awesome 50th anniversary Doctor Who) for any more words.

Week 0, Day 3

Still pretty quiet here. I’ve been helping Ava with her game and looking at some basic tutorials for Backbone and Angular. Then I got sidetracked into learning VIM.

I did hike up the epicness that is Taylor St on a lunch break with Ava to go look at Huntington Park. The views were amazing and I love that I can still wear a T-shirt (no sweater/coat necessary) at all times, even on my evening trek to the BART station and “home” home (Ava was upset by the quotes around the word home so I had to change it).

On the way up:

Up Taylor St

Looking down:

Looking Down Powell St

Looking at the Bay Bridge through the buildings (another thing I love, it looks like stereotypical San Francisco everywhere, tall buildings, funky old fixtures, and a strange mixture of people types):

<img src=”http://res.cloudinary.com/leaena/image/upload/c_scale,h_800/v1391709300/2013-11-06-12_47_39-768x1024_p9tbab.jpg” alt=”Bay Bridge on California St width=”600″ height=”800″>