JavaScript Icon

sequelize: ORM for MySQL and Node.js

Although NoSQL seems to get a lot of attention in Node.js circles, probably because so many document-oriented databases speak JavaScript fluently, wrappers and drivers for relational databases like MySQL are starting to emerge. The latest entry is Sequelize from Sascha Depold. Sequelize provides basic Object-Relational-Mapper (ORM) between your JavaScript objects and MySQL database records.

Install Sequelize via npm:

npm install sequelize

… and require the library:

var Sequelize = require("sequelize").Sequelize

Once the library has been loaded, set up your database connection by creating an instance of Sequelize, with optional host and port.

var sequelize = new Sequelize('database', 'username', 'password', {
  host: "my.server.tld",
  port: 12345

Call the define method to create your models, mapping fields to database types:

var Project = sequelize.define('Project', {
  title: Sequelize.STRING,
  description: Sequelize.TEXT

var Task = sequelize.define('Task', {
  title: Sequelize.STRING,
  description: Sequelize.TEXT,
  deadline: Sequelize.DATE

You can now work with instances of those models with new:

var project = new Project({
  title: 'my awesome project',
  description: 'woot woot. this will make me a rich man'

var task = new Task({
  title: 'specify the project idea',
  description: 'bla',
  deadline: new Date()

Keep in mind that Sequelize was built completely on the Node async architecture, so there are callbacks for most everything, including save():

// way 1
task.title = 'a very different title now'{})

// way 2
  title: 'a very different title now'
}, function(){})

Sequelize also has very slick method chaining to let you batch save objects:

  {save: project}, {save: task}
], function() {
  // woot! saved.

Be sure and check the documentation for more advanced features like Associations and Finder syntax.

[Source on GitHub] [Hompage] [Sascha on Twitter]

0:00 / 0:00