Chapter 13: MySQL

Despite the introduction and increasing popularity of NoSQL, SQL databases are still empowering the majority of applications today.

Node.JS has a rich ecosystem of modules designed to work with SQL databases, especially the one that is the focus of this chapter: MySQL.

In the same fashion as Chapter 12 on MongoDB, here you first learn how to leverage the raw power of the driver (a project called node-mysql). With node-mysql, you write your own SQL queries to interact with the database.

In addition to the driver, you’re going to learn how to use an Object-Relational Mapper (ORM) for MySQL called node-sequelize. As you’ll see, an ORM gives you a mapping between JavaScript instances of a model and data contained in your MySQL database, making it easier to work with relationships, data sanitization, and much more.

node-mysql

To learn how to use node-mysql, you create a few simple models for a shopping cart application.

Setting it up

As usual, you start your application with express, jade, and in this case node-mysql:

package.json

{

    â€œname”: “shopping-cart-example”

  , “version”: “0.0.1”

  , “dependencies”: {

        â€œexpress”: “2.5.2”

      , “jade”: “0.19.0”

      , “mysql”: “0.9.5”

    }

}

The Express app

Next, you create a simple Express app with the following routes:

• /: displays all the items and an item creation form.

• /item/<id>: shows a particular item and its user reviews.

• /item/<id>/review (POST) ...

Get Smashing Node.js: JavaScript Everywhere, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.