Cover by Guillermo Rauch

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

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): creates a review.

/item/create (POST): creates ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required