Sequelize: ActiveRecord for NodeJS
If you are a Ruby on Rails developer, you probably love ActiveRecord that it is too hard for you to imagine using another ORM.
Unfortunately, ActiveRecord is only found in Rails. Luckily for NodeJS developers, there is an awesome alternative which is Sequelize.
Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. It features solid transaction support, relations, read replication and more.
An avid ActiveRecord user myself, I can tell that Sequelize and its CLI are heavily inspired by ActiveRecord.
Migrations
rake db:migrate
or in Rails 5
rails db:migrate
Guess what! With Sequelize CLI it is pretty much the same
sequelize db:migrate
Associations
One-To-One and One-To-Many associations
# AR implementation
class Player < ActiveRecord::Base
belongs_to :team
has_one :jersey
end
// Sequelize implementation
var Player = this.sequelize.define('player', {})
, Team = this.sequelize.define('team', {})
, Jersey = this.sequelize.define('jersey', {})
, Document = this.sequelize.define('document', {});
Player.belongsTo(Team);
Player.hasOne(Jersey);
Player.hasMany(Document, {as: 'Contracts'})
Scopes
Scopes are that easy in ActiveRecord.
class Player < ActiveRecord::Base
scope :retired, -> { where(retired: true) }
end
Well, also for Sequelize
var Project = sequelize.define('project', {},
{
defaultScope: {
where: {
active: true
}
},
scopes: {
retired: {
where: {
retired: true
}
}
}
});
Validations
Sequelize's validations are implemented using validator.js. They are very extensive and useful. Here's an example of a simple User
model with 3 attributes; username
, email
and website
.
var User = sequelize.define('user', {
username: {
type: Sequelize.STRING,
validate: {
is: /^[a-z]+$/i,
isLowercase: true,
notNull: true
}
},
email: {
type: Sequelize.STRING,
validate: {
isEmail: true
}
},
website: {
type: Sequelize.STRING,
validate: {
isUrl: true
}
}
});
For the full list of validations, view the docs.
Querying
You can select only certain attributes in ActiveRecord, for example.
User.select(:name, :email)
In Sequelize, this is how you do it.
User.findAll({
attributes: ['name', 'email']
});
- Where
This is how you query for users assigned to project with id 5
in ActiveRecord
User.where(project_id: 5)
I can barely see any difference!
User.findAll({
where: {
projectId: 5
}
});
You can also use findOne
which is equivalent to User.find_by(project_id: 5)
, it returns only one record matching the criteria.
Get a better insight about the whole sequelize query interface by browsing through querying docs.
Conslusion
I have been using sequelize for a few months now and it is a robust ORM. It still needs some work on handling some minor issues and bugs but in general it is quite reliable.
Contribute to sequelize by submitting PR's to their github repository or add some awesome features to the cli.