JS Questions: What is MongoDB?

This is the fourteenth in a series of posts I’m writing that aims to provide concise, understandable answers to JavaScript-related questions, helping me better understand both foundational concepts and the changing landscape of language updates, frameworks, testing tools, etc.

What is MongoDB?

MongoDB is an open-source database program. There are several database management systems; some of the most popular are Oracle, MySQL, and PostgreSQL. MongoDB has been gaining popularity in recent years and is different from the ones above, because it’s a NoSQL, or non-relational, database management system.

First, Relational Databases…

Relational databases have rows of data stored in tables. A row of data can contain columns with keys that link one record to another. For instance, if there were a relational database containing data about the show Comedians in Cars Getting Coffee, it may have a table for episodes and another table for comedians. Every episode features one comedian (aside from the comedian host, Jerry Seinfeld) so each episode record could have a column called comedian_id that contains a key corresponding with a comedian from the comedian table.

Below is a visual showing how the data would be stored. The only episode in the episodes table has a comedian_id of 2. Kristen Wiig is the comedian in the comedians table with the primary key 2, so she is the comedian for this episode.

Screen Shot 2018-01-22 at 10.47.32 AM.png

Using the database querying language, SQL, tables can reference each other’s data through JOIN statements. Here’s an example:

SELECT Episodes.Title, Comedians.Name FROM Episodes INNER JOIN Comedians ON Comedian.Id = Episodes.Comedian_id;

This is saying: show episode titles with their corresponding comedian names by using the episode’s comedian_id to find the comedian with an id of the same number.

Now, NoSQL Databases…

Records are stored differently with MongoDB. Instead of table rows, data is stored in JSONlike documents.

A document can contain nested information. For instance, an episode document may contain a nested comedian document. Or, a document for the show’s seasons could have a nested array of episodes.

Below is an example of what a document might look like for an episode with one comedian.


A grouping of documents–all comedians, for example–is called a collection. It’s the equivalent to a table in a relational database, though unlike a relational database, items do not need to have the same schema.

The mongo shell can be used to interact with a database and perform actions, such as retrieving all documents from a collection. The below code would grab all comedians from a database (db) with a comedians collection, using the .find() operation:


Since documents can store nested data (such as an episode’s comedian), the need to perform a costly ‘join’ in order to access data is reduced. (MongoDB does have the functionality to join collections when needed.)

MongoDB in context…

MongoDB is generally associated with the latest wave of web applications and tech startups. Of course, different database management systems are suitable for different projects, but these are a few reasons (I think) MongoDB is gaining momentum.

MongoDB is well suited to the Agile style of software development that has become popular. Engineers using a quick, iterative development approach can easily change their schema and models as needed.

For startups and fast growing applications, there’s also the benefit of MongoDB’s distributed database design. Data is stored across multiple machines by default, so the database can easily expand as needed.

The 2017 Stack Overflow Developer Survey has a correlated technologies graph showing MongoDB closely linked with the frameworks Angular, Node.js, React, and Cordova, as well as the languages, JavaScript and TypeScript (a syntactical superset of JavaScript). While it’s not necessary to pair MongoDB and JavaScript (there are several ‘drivers‘ that can be used to interact with MongoDB with different programming languages), building full stack applications entirely with JavaScript is growing in popularity. Two common stacks for building modern web applications are MEAN (MongoDB, Express, Angular, Node.js) and MERN (MongoDB, Express, React, Node.js).

Part of the excitement about MongoDB can also be attributed to the fact that it’s new, has an excited community, growing features, and pretty approachable documentation and educational features on the MongoDB site.

Final note: There’s a lot of debate about whether MongoDB is better than SQL options. MongoDB may be faster in some cases (such as the previous example of reading an episode’s comedian), but SQL databases have their own advantages, including the reliability of a mature system (Oracle has been around since 1977). This Sitepoint article offers an introduction to best use-cases for SQL and NoSQL databases.




Testing Locally Hosted Site on Phone

I’ve been building a Rails app with mobile, tablet, and desktop views using Materialize CSS and wanted to be able to test the site on my Android phone to make sure sizing and touchscreen links are user-friendly.

Localhost.run turned out to be a quick solution. After running an app on port 8080, you can run Localhost’s command and get a url to view the site from another device for preview and testing.

For a Rails app, start the server on port 8080.

rails s -p 8080

Then, run Localhosts’ command in another Terminal window.

ssh -R 80:localhost:8080 -p 2222 ssh.localhost.run

LocalHost will print the url to visit in Terminal.


JS Questions: What is Express?

This is the thirteenth in a series of posts I’m writing that aims to provide concise, understandable answers to JavaScript-related questions, helping me better understand both foundational concepts and the changing landscape of language updates, frameworks, testing tools, etc.

What is Express?

The backend framework Express, released in 2010 and supported by Node.js, can be used to handle routing, generate ‘views’ for request responses, and define an application’s basic specifications. Express can be used with any database that Node supports, such as MongoDB, PostgreSQL, and Redis (though it’s not necessary to use a database with Express).

The following code creates a server without using Express. The server runs on port 3000, allowing a user to go to “localhost:3000/” and see the string “Hello World!”.

This illustrates that it’s not necessary to use Express to employ Node’s HTTP request response cycle. However, Express makes it easier to define routes and set up some basic specifications for an app. After installing Express, the following code should also render “Hello World!” at “localhost:3000/”:

Express’s website describes the framework as “fast, unopinionated, minimalist,” because its simply a layer on top on Node.js that allows developers use any file structure, pattern, or additional middleware they choose. This makes it easy to build simple applications without unnecessary bulk.

Express is used in production by some high profile companies (Uber, IBM, MuleSoft, to name a few) and is a part of the JavaScript stacks MEAN (Mongo, Express, Angular, Node) and MERN (Mongo, Express, React, Node).



JS Questions: How are JSON Web Tokens Used?

This is the twelfth in a series of posts I’m writing that aims to provide concise, understandable answers to JavaScript-related questions, helping me better understand both foundational concepts and the changing landscape of language updates, frameworks, testing tools, etc.

How are JSON Web Tokens Used?

JSON web tokens (JWT) are a publicly-available system that enables secure transmissions between two parties. The technology is not JavaScript specific, but is useful in applications that must make verified requests to a server, such as a React front-end application requesting a user’s password-protected information through a fetch request. The JWT does not authenticate a user, but rather sends along the information needed to verify that the client making the request has been authenticated.

JTWs are popular for a few reasons. First, of all, because the tokens require a server-side decryption, they can’t be easily manipulated by the user or a third party. They’re also compact (preventing a bloated post request) and self-contained, meaning they don’t require a followup request for data after the authentication is made.

Here’s how a JWT might be used alongside the user authentication process to allow a client to access their password-protected information:

  1. A user enters their login information and their credentials are posted to a server. Upon confirming that the user has entered the proper information, a JWT can be created.
  2.  The JWT has three parts: 

Header: The header contains indication that it is a JTW token, as well as the type of hashing algorithm used, both stored in JSON format. A hashing algorithm is a type of function used to encrypt and decrypt data.

This header is base64 encoded, meaning that its data is locked in a format that won’t be modified in the transmission process. 

Payload: Also formatted in JSON, the payload contains the data being sent. This is where information such as a user’s id or unique username may be stored. This section can also store the token’s expiration date. 

The resulting JSON is base64 encoded.

Signature: This takes the encoded header and payload, as well as the algorithm indicated in the header, and a generated secret to create a signature.

Finally, the token can be created in the correct format: three parts separated by dots: header.payload.signature

3. The created JWT token is sent back to the client in the request’s response.

4. The token is stored in the client’s local browser storage so that it won’t be lost upon the page refreshing.

5. Every time the user requests information that is protected, the token is sent along in the header of the post request.

6. Each time the access token is sent with a request, it can be decoded using the secret stored on the server-side. No database query is needed to authenticate the request. The signature verifies that the token is coming from the right sender and that the data is not manipulated.

Note: I’ve referred to a secret key used to verify the token. The key is like a password that can be used to unlock private information. Just like a password, it can be changed and should be stored in a secure place. The HMAC algorithm uses a secret to encode and decode. RSA is another algorithm that uses public and private keys. Either system can be used with JWT. 


JS Questions: What’s the Event Loop?

This is the eleventh in a series of posts I’m writing that aims to provide concise, understandable answers to JavaScript-related questions, helping me better understand both foundational concepts and the changing landscape of language updates, frameworks, testing tools, etc.

What’s the Event Loop?

Like any programming language, JavaScript has a specific process for handling function calls in a program, and more specifically, deciding when each function will run. Unlike other languages, JavaScript can be run in a browser, meaning that users may be interacting with the program by clicking a mouse or scrolling, for instance, simultaneous to other processes that are already running. The event loop helps create a fluid experience for users, by dictating a flow that allows for relatively long running processes to occur alongside client-side interactions.

Without features built into Node and browsers, JavaScript would only be able to handle one event at a time. Each function call would be added to a stack and one-by-one, popped off the top and run. It’s easy to imagine how this could become problematic in a web app. If a notice telling a user she had successfully updated her account were rendered to a webpage for three seconds using setTimeout, the user would not be able to interact with the page until the setTimeout had completed.

Some events do happen synchronously in JS. Loops will run in the call stack and prevent a webpage from re-rendering until they have completed.

However, due to the event loop built into browsers, processes such as AJAX requests and timeouts can run in the background, with their callback functions placed in a queue that are added to the call stack only when the entire stack has cleared. The below code snippet illustrates this.

If you paste this in your console, you’ll see 1 logged, then 2 returned, then 3 logged. Here’s what happens:

  1. The eventLoop function gets added to the call stack.
  2. The setTimeout timer begins and the callback function is added to the queue after 0 milliseconds.
  3. The number 1 is immediately logged.
  4. The eventLoop function returns 2 and the call stack is cleared.
  5. The setTimeout callback runs, logging 3.

Note that the call stack runs functions in ‘first in last out’ order (meaning that the first function added to a stack is the last to run). That’s why, in the code below, the strings are already concatenated when logged:

First, the greet function is added to the call stack. Then, the concat function is added to the call stack. Concat runs, the greeting is logged, and the greet function is cleared from the stack.

Meanwhile, the queue runs callback functions in ‘first in first out’ order. The first item added to the queue is the first to be added to the call stack. That means, if multiple AJAX requests are made, for instance, the first request to finish will be the first to have its callback function run.

In sum, the event loop in JavaScript refers to the synchronous and asynchronous flow dictated by the call stack and queue in browsers.



Building a Blog with PDF Uploader in Rails 5


Build a blogging feature for use on a nonprofit corporation website. Implement create, read, update, and delete actions for the blog, which will be used to make public announcements with PDFs attached.



Within an existing Rails 5 app, use the Trix gem and the Paperclip gem along with basic Rails features to build CRUD actions for a blog post.


Add gems to the gemfile and run bundle

  1. gem "paperclip","~> 5.0.0"
  2. gem 'trix'

Follow Paperclip install instructions

For Mac OS X, I did:

  1. Install an image processor: brew install imagemagick.
  2. Because I want PDF uploads, I also needed Ghostscript:
    brew install gs

Follow Trix install instructions

  1. In the application stylesheet (a css or scss file in the assets directory), paste
    *= require trix
  2. In the application.js file (also in the assets directory), paste //= require trix

Create relationships and validations in models

I created validations for a post to have a title and content. Paperclip also has a validation for an document’s content type, as well as a required has_attached_file method, where specifications can be added such as the file’s width and height (more likely used for an image than a PDF).
class Post < ApplicationRecord

belongs_to :user
validates :title, presence: true
validates :content, presence: true
has_attached_file :document
validates_attachment_content_type :document, :content_type => ['application/pdf']


class User < ApplicationRecord

has_many :posts



I generated a migration for posts and later ran a Paperclip migration. The Paperclip migration gives a datatype of attachment, which is reflected in the schema after the migration has been run with four new columns: the attachment name, content type, file size, and time of update. (This can also be run as one migration. Check out the Paperclip documentation.)

  1. rails generate migration CreatePosts title:string user_id:integer content:text
  2. rails generate paperclip post document


I want full CRUD actions for my users and posts, so I used Rails resources.

resources :users
resources :posts


I haven’t included my entire posts controller, but as an example, here’s the create controller action with strong params. Check out my github repository to see all of my controller actions.

class PostsController < ApplicationController

def create
@post = Post.new(post_params)
@post.user = current_user
# current_user is a method defined in the Application Controller
if @post.save
flash[:notice] = "Post published!"
redirect_to :users
flash[:notice] = "posts must have a title and content"
render 'new'


def post_params
params.require(:post).permit(:title, :content, :document)



To add a Trix text editor in my post new and post edit view, I simply used Trix’s built-in method, which can be used with Rails form_for.

The Paperclip attachment is equally easy to implement with form_for using the file_field method.

New Post Form

<%= form_for @post do |f| %>
<%= f.label :title %>
<%= f.text_field :title %>

<%= f.label :content %>
<%= f.trix_editor :content %>

<%= f.label :document %>
<%= f.file_field :document %>

<%= f.submit 'submit', :class => "waves-effect waves-light amber lighten-1 white-text btn" %>
<% end %>

Post Show Page

When rendering the post content, I used the Rails sanitize method in order to safely render user input. Sanitize removes any non-whitelisted content from the html.

<%= @post.title %>
<%= link_to @post.upload_attachment_file_name, @post.upload_attachment.url %>
<%= sanitize @post.content %>


While I’ve removed some unnecessary code for simplicity and readability, these steps include everything needed to create a functioning blog feature. Check out my github repository to see the full project.


Rails Nested Forms: Collection Checkboxes

I recently figured out a couple tricks for using collection check boxes in a Rails 5 project with Materialize styling.

My goal: Have users check or uncheck programs associated with a classroom. A classroom can have many programs, so I used the Rails collection checkboxes form helper to allow multiple selections.

Implementation: The collection checkboxes form helper generates a labelled checkbox for each item in a collection.

Above, the first argument of collection checkboxes is :program_ids. This represents the method, program_ids, available on each classroom instance. It also will be the name of the key I can access in my params which has the value of all selected program ids.

I passed in @programs as the second argument, which is the collection of programs pulled from my database in my Classrooms controller.

The third argument, :id, refers to the data that will be passed into my params. In this case, I’m going to send the program ids, so that in my Classrooms controller, I can find programs by id in my database.

The final argument, :title, refers to the program’s title, which will be used to label each checkbox so the user will know which program they’re checking or unchecking.

When I added this code to my form, my checkboxes and labels were properly generated, but there was no spacing or formatting. I wanted each program to render on a new line, so I iterated through each program and added divs wrapping the checkbox and label.

When I first implemented the iteration, I had reversed the order of the checkbox and label, and my checkboxes were not appearing. I read a handy Stack Overflow post, which explained that the checkbox must appear before the label when using MaterializeCSS.

Next, I used strong params to access my array of checked programs, and update the classroom’s programs in my Classrooms controller’s update method. While I ultimately ended up refactoring my controller, this was my initial approach:

I used the delete_if method on line five, because the array of ids in my params included empty strings for unchecked boxes.

Refactor: I suspected that there was a more efficient way to update the classroom’s programs from my array of program ids in the Classrooms controller, since my original version involved two iterations and several database calls.

It turns out that I had made the job of updating my associations much more difficult for myself than necessary. In fact, I can simply pass the classroom’s update method my array of program ids, and it’ll take care of the rest: