bookshelf、objection、sequelize、typeorm は、Node.js アプリケーションでデータベース操作を抽象化するための ORM(オブジェクト関係マッピング)ライブラリです。これらを使うことで、生の SQL を直接書くことなく、JavaScript や TypeScript のオブジェクトを通じてデータベースの作成、読み取り、更新、削除(CRUD)を行えます。sequelize と typeorm は包括的な機能セットを提供し、objection と bookshelf はクエリビルダーである knex.js を基盤としています。フロントエンド開発者がフルスタック構成を選ぶ際、これらの違いを理解することは、バックエンドの保守性と開発速度に直結します。
Node.js でデータベースを扱う際、bookshelf、objection、sequelize、typeorm の 4 つが主要な選択肢となります。これらはすべて ORM として機能しますが、設計思想や TypeScript への対応、メンテナンス状況に大きな違いがあります。フロントエンド開発者がバックエンドも担当するフルスタック環境では、これらの選定がプロジェクトの長期維持性に影響します。ここでは、実務で直面するモデル定義、クエリ実行、リレーションシップ処理の観点から比較します。
比較に入る前に、bookshelf の現状について触れておく必要があります。bookshelf はかつて人気がありましたが、現在は開発活動が非常に低調です。公式のドキュメントやリポジトリの更新頻度から、実質的にメンテナンスモードに入っていると見なされています。新規プロジェクトでこれを選ぶ理由はほぼなく、同じ knex.js ベースであれば objection を使うのが現代の標準です。以下の比較には含めますが、採用は推奨しません。
ORM の最初のステップは、データベースのテーブルをコード上で定義することです。ここで各ライブラリの書き方の違いがはっきり出ます。
sequelize はクラス拡張スタイルを採用しています。v6 以降ではモデルをクラスとして定義し、init メソッドでカラムを指定します。
// sequelize
const { Model, DataTypes } = require('sequelize');
class User extends Model {}
User.init({
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
name: { type: DataTypes.STRING, allowNull: false }
}, { sequelize, modelName: 'user' });
typeorm は TypeScript のデコレータ構文を使います。クラスプロパティにデコレータを付けることで、型情報と DB 定義を一元管理できます。
// typeorm
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
}
objection は knex.js のテーブル名を静的プロパティで定義し、JSON Schema でバリデーションを設定します。
// objection
const { Model } = require('objection');
class User extends Model {
static get tableName() {
return 'users';
}
}
bookshelf は extend メソッドを使ってモデルを生成する、やや古いパターンを採用しています。
// bookshelf
const bookshelf = require('./bookshelf-instance');
const User = bookshelf.Model.extend({
tableName: 'users'
});
データ取得時の記述量は、開発速度に直結します。特に TypeScript を使う場合、型推論の効きやすさが重要です。
sequelize は findAll や findOne といった直感的なメソッドを提供します。オプションオブジェクトで条件を指定します。
// sequelize
const users = await User.findAll({
where: { name: 'Alice' },
order: [['id', 'DESC']]
});
typeorm はリポジトリパターンまたはエンティティマネージャーを使います。クエリビルダーチェーンも利用可能です。
// typeorm
const users = await userRepository.find({
where: { name: 'Alice' },
order: { id: 'DESC' }
});
objection はクエリビルダーチェーンをそのまま使えます。SQL に近い感覚でメソッドを繋げられます。
// objection
const users = await User
.query()
.where('name', 'Alice')
.orderBy('id', 'desc');
bookshelf も query メソッドを通じて knex の機能を利用しますが、ラッパーを介す分、記述が少し冗長になります。
// bookshelf
const users = await User
.query({ where: { name: 'Alice' } })
.orderBy('id', 'desc')
.fetchAll();
テーブル間の関連(1 対多、多対多など)をどう定義するかも重要なポイントです。
sequelize は hasMany や belongsTo を使ってモデル間で関連を定義します。定義後に include オプションで結合します。
// sequelize
User.hasMany(Post);
const userWithPosts = await User.findOne({
where: { id: 1 },
include: [Post]
});
typeorm はデコレータでリレーションを定義します。@OneToMany などで型安全に関連を張ります。
// typeorm
@OneToMany(() => Post, post => post.user)
posts: Post[];
// 取得時
const user = await userRepository.findOne({
where: { id: 1 },
relations: ['posts']
});
objection は relationMappings をモデル内に定義します。遅延読み込みが可能で、循環参照を防ぎやすい構造です。
// objection
class User extends Model {
static get relationMappings() {
return {
posts: {
relation: Model.HasManyRelation,
modelClass: Post,
join: { from: 'users.id', to: 'posts.user_id' }
}
};
}
}
const user = await User.query().findById(1).withGraphFetched('posts');
bookshelf は hasMany などをプロパティとして定義します。fetch 時に withRelated を指定して関連データを取得します。
// bookshelf
const User = bookshelf.Model.extend({
tableName: 'users',
posts: function() {
return this.hasMany(Post);
}
});
const user = await User.where({ id: 1 }).fetch({ withRelated: ['posts'] });
ライブラリの選び方は、単なる機能比較だけでなく、将来のメンテナンス性を考慮する必要があります。
| 特徴 | sequelize | typeorm | objection | bookshelf |
|---|---|---|---|---|
| TypeScript | 対応(後付) | ネイティブ対応 | 対応 | 限定的 |
| 基盤 | 独自 | 独自 | knex.js | knex.js |
| 学習曲線 | 緩やか | 中程度 | 中程度 | 緩やか |
| メンテナンス | 活発 | 活発 | 活発 | 低調 |
sequelize は機能が豊富ですが、その分 API が庞大です。typeorm は TypeScript との相性が良く、コンパイル時にエラーを検出できるため、大規模プロジェクトで有利です。objection は SQL を直接書きたい場合の柔軟性が魅力ですが、knex の知識が少し必要になります。
新規プロジェクトで ORM を選ぶ場合、以下の基準で決定するのが現実的です。
TypeScript を本格的に使うなら typeorm
型安全性とデコレータによる定義のしやすさが、リファクタリング時の安心感につながります。NestJS を使う場合はほぼ一択です。
安定性と情報量なら sequelize
困ったときに検索すればすぐ解決策が見つかります。JavaScript メインのプロジェクトや、ORM の機能に依存したい場合に適しています。
SQL 制御を重視するなら objection
複雑なクエリを ORM に任せきらず、必要に応じて SQL に近づけたい場合に最適です。
bookshelf は避ける
既存システムを維持する場合を除き、新規採用は推奨しません。コミュニティのサポートが得られにくくなるリスクがあります。
最終的には、チームの TypeScript 習熟度と、SQL への依存度によって選ぶのが良いでしょう。どれを選んでも CRUD 操作は可能ですが、長期的な開発のしやすさは typeorm と sequelize が頭一つ抜けています。
typeorm を選ぶべきは、TypeScript を-first で開発するプロジェクトです。デコレータを使った定義は型安全性が高く、NestJS などのフレームワークとの相性が抜群です。エンティティベースの設計が好みで、コンパイル時のエラー検出を重視するチームに推奨されます。
sequelize は最も歴史があり、コミュニティが大きい ORM です。安定性を最優先し、豊富なプラグインやドキュメントを必要とする場合に適しています。JavaScript ベースのプロジェクトや、TypeScript を深く使い込まないチームにとって、学習コストが低く導入しやすい選択肢です。
objection を選ぶべきなのは、knex.js の柔軟性を保ちつつ ORM 機能が必要な場合です。クエリビルダーとしての制御性を重視し、SQL との親和性を高めたいプロジェクトに適しています。TypeScript サポートもあり、複雑なクエリを扱う場合に威力を発揮します。
bookshelf は knex.js に依存する古い ORM であり、現在はメンテナンスモードに入っています。既存のレガシープロジェクトを維持する場合を除き、新規プロジェクトでの採用は避けるべきです。コミュニティの支持は objection に移行しており、長期的なサポートを考えると代替案を検討するのが賢明です。
TypeORM is an ORM that can run in Node.js, Browser, Cordova, Ionic, React Native, NativeScript, Expo, and Electron platforms and can be used with TypeScript and JavaScript (ES2021). Its goal is to always support the latest JavaScript features and provide additional features that help you to develop any kind of application that uses databases - from small applications with a few tables to large-scale enterprise applications with multiple databases.
TypeORM supports more databases than any other JS/TS ORM: Google Spanner, Microsoft SqlServer, MySQL/MariaDB, MongoDB, Oracle, Postgres, SAP HANA and SQLite, as well we derived databases and different drivers.
TypeORM supports both Active Record and Data Mapper patterns, unlike all other JavaScript ORMs currently in existence, which means you can write high-quality, loosely coupled, scalable, maintainable applications in the most productive way.
TypeORM is highly influenced by other ORMs, such as Hibernate, Doctrine and Entity Framework.
And more...
With TypeORM, your models look like this:
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column()
firstName: string
@Column()
lastName: string
@Column()
age: number
}
And your domain logic looks like this:
const userRepository = MyDataSource.getRepository(User)
const user = new User()
user.firstName = "Timber"
user.lastName = "Saw"
user.age = 25
await userRepository.save(user)
const allUsers = await userRepository.find()
const firstUser = await userRepository.findOneBy({
id: 1,
}) // find by id
const timber = await userRepository.findOneBy({
firstName: "Timber",
lastName: "Saw",
}) // find by firstName and lastName
await userRepository.remove(timber)
Alternatively, if you prefer to use the ActiveRecord implementation, you can use it as well:
import { Entity, PrimaryGeneratedColumn, Column, BaseEntity } from "typeorm"
@Entity()
export class User extends BaseEntity {
@PrimaryGeneratedColumn()
id: number
@Column()
firstName: string
@Column()
lastName: string
@Column()
age: number
}
And your domain logic will look this way:
const user = new User()
user.firstName = "Timber"
user.lastName = "Saw"
user.age = 25
await user.save()
const allUsers = await User.find()
const firstUser = await User.findOneBy({
id: 1,
})
const timber = await User.findOneBy({
firstName: "Timber",
lastName: "Saw",
})
await timber.remove()
Take a look at the samples in sample for examples of usage.
There are a few repositories that you can clone and start with:
There are several extensions that simplify working with TypeORM and integrating it with other modules:
data-source.ts after generating migrations/entities - typeorm-codebase-syncrelations objects - typeorm-relationsrelations based on a GraphQL query - typeorm-relations-graphqlLearn about contribution here and how to set up your development environment here.
This project exists thanks to all the people who contribute:
Open source is hard and time-consuming. If you want to invest in TypeORM's future, you can become a sponsor and allow our core team to spend more time on TypeORM's improvements and new features.
Become a champion sponsor and get premium technical support from our core contributors. Become a champion
Support TypeORM's development with a monthly contribution. Become a supporter
Join our community of supporters and help sustain TypeORM. Become a community supporter
Make a one-time or recurring contribution of your choice. Become a sponsor