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.

mongo_ex.png

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:

db.comedians.find()

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.

Resources

 

Advertisements

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).

Resources

 

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. 

Resources

JS Questions: What is Webpack?

This is the tenth 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 Webpack?

JavaScript-based applications have increasingly complex systems and interactions. They send and receive data; they create a user interface; they have non-JavaScript assets such as styling and images; and they incorporate outside packages of reusable code. The purpose of Webpack is to bring together all the disparate parts and turn them into one file, made readable to the browser rendering the application. This job is called module bundling. 

There are two types of ways that code is transformed in Webpack and these processes are handled by separate entities: loaders and plugins.

Loaders take in the application’s files, turn them into modules that can be read by a JavaScript engine, and add the modules to a dependency graph. A dependency graph is like a map (written in JS) showing how each module is related to other modules.

Different loaders can handle different tasks in the transformation process. The babel-loader, for example, takes in ES2015 (or later) code and transpiles the code to an earlier version of JS syntax.

While loaders create modules, plugins alter the modules to optimize them for computer processing, dependency injection, debugging, and other tasks. The UglifyJS plugin, for example, minifies code in order to make it run faster. 

When all dependencies have been added to the graph and all processes have been run, the static file is handed off to the browser to load.

Webpack can be configured with whichever loaders and plugins a project needs, though there’s also an ‘out-of-the-box’ option for React developers. React, a popular library for building JS front end, has community support for Webpack. The package, Create React App, can be used to generate files for a new React application preconfigured with Webpack. The Webpack-enabled functionality, including hot reloading (which adds, removes, or updates modules, without a page needing to fully reload) make it especially handy.

Other module bundlers exist (Browserify is considered the first of its kind), but Webpack has become an industry favorite.

 

Resources:

JS Questions: What is Node.js?

This is the ninth 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 Node.js?

Unlike Ruby (and many other programming languages), JavaScript wasn’t built to be executed outside of the browser. A Ruby program can be run by simply typing the path to the file to be run prepended by ‘ruby’ in terminal:

ruby filename.rb

Node.js (also called simply Node), which is built on the Chrome V8 JavaScript Engine, can be used to run JavaScript code outside of the browser. To try it, download Node and run the Javascript file from terminal:

node filename.js

Nodejs.org refers to Node as a runtime. Runtime environments dictate how a program is executed. All runtime environments have an event loop, or set of instructions how a programming language handles incoming events and dispatches them.

A ‘non-blocking I/O model’ differentiates Node from other runtime environments. Input and output (I/O) refers to the interaction between the processing system and user or other input making a request. A user clicks their mouse, for example, and the server returns requested data rendered in the browser.

In contrast to a non-blocking model, a blocking I/O is one in which JS code cannot run until the previous operation is complete. In other words, the event loop pauses until the process finishes. Node allows asynchronous, non-blocking events to occur, meaning that a process doesn’t need to finish in order for another to start. This allows an application to handle frequent incoming requests with minimal downtime.

Node is widely used to make server-side applications. The server side of an app takes in requests and responds with data to the front end of the application. This allows requests to create, update, or delete data to be persisted in a database, as well as for information to be accessed from the database and rendered in the front end.

Scalability, low latency, and high bandwith are often noted as key benefits of using Node over other server-side options, due to its non-blocking I/O. More information about how Node works as compared to Ruby’s Event Machine, for example, is available on nodejs.org.  There’s also a ‘hello world’ example for creating a server with Node and hosting it on a port.

Node also has a popular JavaScript package manager, npm, which allows developers to install JavaScript packages, pieces of software made available to developers to download and use with their own projects. Some commonly downloaded JS packages include express, react, and babel-core.

“Node’s package manager, npm, has transformed from hosting utility modules for server-side apps to the canonical place to store distributable JavaScript code.” –The future of Javascript in 2017 and Beyond

Finally, node is also open source and has a community of contributors.

Resources

 

 

JS Questions: What’s a JavaScript Engine?

This is the eighth 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 a JavaScript Engine?

JS engines interpret and execute JavaScript code, usually for a web browser (since JS was created to run in the browser). They are written in lower-level languages such as C++ and C.

An engine must receive the specific version of JavaScript that it has been built to interpret. (There are several versions of JavaScript, as the language becomes updated and optimized for development. The most recent version is ES2017, which can be transpiled to an earlier version of JS in order to be run by a JS engine.)

Browsers have an increasing need to efficiently interpret JS code, because web applications more heavily rely on Javascript, not just to run a few scripts, but as their framework language. While popular modern browsers all have JS engines, there’s still a lot of competition among them to have the fastest engine that can generate the most optimized code.

Examples of JS Engines

  • V8 (Chrome)
  • Spidermonkey (Mozilla)
  • JavaScript Core (Safari)
  • Chakra (IE)

 

Resources

JS Questions: What’s a Transpiler?

This is the seventh 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 a Transpiler?

JavaScript transpilers emerged when the latest big update to JavaScript (ES2015) was released, which brought about some major changes to the language (such as arrow functions and classes). These updates have been good for developers, making it easier to write code in an intuitive and concise manner.

Before ES2015, the most recent update to the language had been in 2009, and since 2015, two more updates have been released, ES2016 and ES2017. With the recent rapid changes to JS, web browsers like Chrome, Firefox, and Safari have been unable to maintain compatibility with the language, and transpilers are used to bridge the gap between them.

This table breaks down different browsers’ compatibility with JS versions by feature, giving a sense of the types of issues that must be accounted for by web browsers with language updates.

Transpilers such as Babel take care of this compatibility issue by transforming code to follow earlier conventions the browser can support. Essentially, a transpiler allows a programmer to have the convenience of coding in the most recent version of JS, while still being able to revert the code to an earlier standard. The transpiled code probably won’t be as readable as it would be if it had been written by a programmer (check out Babel’s repl to test this), but it shouldn’t matter–transpiled code will be handed off to the compiler to transform into computer-readable code.

Sources