SEQUELIZE

ORM for Node.js

@khriztianmoreno

Cristian Moreno

FullStack Javascript Developer

I'm a community leader and altruistic speaker, JavaScript evangelist. Currently co-organize Medellin.js (Biggest JavaScript user group in Colombia), Avanet and .NETConf.

Agenda

  • Introduction - ORM
  • Sequelize
  • Install - Setup - Connection
  • Models
    • Data types
    • Associations
  • Querying
  • CLI

ORM

Object-Relational Mapping 

A layer between the application and persistence

ORM

Avoid the need to write raw SQL

Become

ORM

ORM

Another commercial solutions

JAVA

PHP

.NET

SEQUELIZE

Sequelize is a promise-based Node.js ORM for Postgres, MySQL, SQLite and Microsoft SQL Server. It features solid transaction support, relations, read replication and more.

SEQUELIZE

  • Entirely written in JavaScript
  • Support for migrations
  • Supported databases
    • PostgreSQL, MySQL, SQLite and MSSQL
  • Current Version: 6.19.0

Installation

Sequelize is available via npm

Setting up a Connection

Models

Represent tables

Models

You can set options on each column

Models

Data Types

Association

You can specify associations between multiple modules


Automatically create indexes to control the relationship between tables 

 

  • One-To-One
  • One-To-Many
  • Many-To-Many

One-To-One Association

Connect one source with exactly one target.
Methods belongsTo() and hasOne().

One-To-Many Association

Connect one source with multiple targets.
Targets however are connected to only one source.

 

Many-To-Many Association

Connect multiple resources with multiple targets

Will create a new model called ProjectUsers

Many-To-Many Association

You can specify the name of an existing join table

Many-To-Many Association

You can also add attributes to the join table

Associating objects

Because Sequelize is doing a lot of magic, you have to call Sequelize.sync after setting the associations! 

Querying

find()   // returns a single entry

Finders

findOrCreate()   // Check if an element exists and if not, create it

The success callback function will receive the retrieved/created user and the flag 'created'

Finders

findAndCountAll()   // Returns an object with two properties, the total number of records and an array of objects containing the records

 

Finders

findAll()   // Search for multiple elements in the database

 

Sequelize CLI

More to know

  • Validations
  • Instances
  • Hooks
  • Getters & Setters
  • Raw Queries
  • Sync
  • Migrations

Resources

Thanks 🙇🏼 🙏🏼 👨🏼‍💻

Sequelize 101

By Khriztian Moreno

Sequelize 101

Sequelize is a promise-based ORM for Node.js. It supports the dialects PostgreSQL, MySQL, MariaDB, SQLite and MSSQL.

  • 2,482