typeorm vs sequelize vs objection vs bookshelf
Node.js 環境における ORM ライブラリの選定ガイド
typeormsequelizeobjectionbookshelf類似パッケージ:

Node.js 環境における ORM ライブラリの選定ガイド

bookshelfobjectionsequelizetypeorm は、Node.js アプリケーションでデータベース操作を抽象化するための ORM(オブジェクト関係マッピング)ライブラリです。これらを使うことで、生の SQL を直接書くことなく、JavaScript や TypeScript のオブジェクトを通じてデータベースの作成、読み取り、更新、削除(CRUD)を行えます。sequelizetypeorm は包括的な機能セットを提供し、objectionbookshelf はクエリビルダーである knex.js を基盤としています。フロントエンド開発者がフルスタック構成を選ぶ際、これらの違いを理解することは、バックエンドの保守性と開発速度に直結します。

npmのダウンロードトレンド

3 年

GitHub Starsランキング

統計詳細

パッケージ
ダウンロード数
Stars
サイズ
Issues
公開日時
ライセンス
typeorm3,627,05336,37120.8 MB5203ヶ月前MIT
sequelize2,624,09830,3492.91 MB1,0122日前MIT
objection252,7967,351645 kB1281年前MIT
bookshelf57,1446,364-2386年前MIT

Node.js ORM 徹底比較:Sequelize、TypeORM、Objection、Bookshelf

Node.js でデータベースを扱う際、bookshelfobjectionsequelizetypeorm の 4 つが主要な選択肢となります。これらはすべて ORM として機能しますが、設計思想や TypeScript への対応、メンテナンス状況に大きな違いがあります。フロントエンド開発者がバックエンドも担当するフルスタック環境では、これらの選定がプロジェクトの長期維持性に影響します。ここでは、実務で直面するモデル定義、クエリ実行、リレーションシップ処理の観点から比較します。

⚠️ 重要な注意点:Bookshelf の現状

比較に入る前に、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;
}

objectionknex.js のテーブル名を静的プロパティで定義し、JSON Schema でバリデーションを設定します。

// objection
const { Model } = require('objection');

class User extends Model {
  static get tableName() {
    return 'users';
  }
}

bookshelfextend メソッドを使ってモデルを生成する、やや古いパターンを採用しています。

// bookshelf
const bookshelf = require('./bookshelf-instance');

const User = bookshelf.Model.extend({
  tableName: 'users'
});

🔍 データの取得クエリ

データ取得時の記述量は、開発速度に直結します。特に TypeScript を使う場合、型推論の効きやすさが重要です。

sequelizefindAllfindOne といった直感的なメソッドを提供します。オプションオブジェクトで条件を指定します。

// 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');

bookshelfquery メソッドを通じて knex の機能を利用しますが、ラッパーを介す分、記述が少し冗長になります。

// bookshelf
const users = await User
  .query({ where: { name: 'Alice' } })
  .orderBy('id', 'desc')
  .fetchAll();

🔗 リレーションシップ(関連付け)

テーブル間の関連(1 対多、多対多など)をどう定義するかも重要なポイントです。

sequelizehasManybelongsTo を使ってモデル間で関連を定義します。定義後に 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']
});

objectionrelationMappings をモデル内に定義します。遅延読み込みが可能で、循環参照を防ぎやすい構造です。

// 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');

bookshelfhasMany などをプロパティとして定義します。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'] });

🛠️ 保守性とエコシステム

ライブラリの選び方は、単なる機能比較だけでなく、将来のメンテナンス性を考慮する必要があります。

特徴sequelizetypeormobjectionbookshelf
TypeScript対応(後付)ネイティブ対応対応限定的
基盤独自独自knex.jsknex.js
学習曲線緩やか中程度中程度緩やか
メンテナンス活発活発活発低調

sequelize は機能が豊富ですが、その分 API が庞大です。typeorm は TypeScript との相性が良く、コンパイル時にエラーを検出できるため、大規模プロジェクトで有利です。objection は SQL を直接書きたい場合の柔軟性が魅力ですが、knex の知識が少し必要になります。

💡 結論と推奨

新規プロジェクトで ORM を選ぶ場合、以下の基準で決定するのが現実的です。

  1. TypeScript を本格的に使うなら typeorm 型安全性とデコレータによる定義のしやすさが、リファクタリング時の安心感につながります。NestJS を使う場合はほぼ一択です。

  2. 安定性と情報量なら sequelize 困ったときに検索すればすぐ解決策が見つかります。JavaScript メインのプロジェクトや、ORM の機能に依存したい場合に適しています。

  3. SQL 制御を重視するなら objection 複雑なクエリを ORM に任せきらず、必要に応じて SQL に近づけたい場合に最適です。

  4. bookshelf は避ける 既存システムを維持する場合を除き、新規採用は推奨しません。コミュニティのサポートが得られにくくなるリスクがあります。

最終的には、チームの TypeScript 習熟度と、SQL への依存度によって選ぶのが良いでしょう。どれを選んでも CRUD 操作は可能ですが、長期的な開発のしやすさは typeormsequelize が頭一つ抜けています。

選び方: typeorm vs sequelize vs objection vs bookshelf

  • typeorm:

    typeorm を選ぶべきは、TypeScript を-first で開発するプロジェクトです。デコレータを使った定義は型安全性が高く、NestJS などのフレームワークとの相性が抜群です。エンティティベースの設計が好みで、コンパイル時のエラー検出を重視するチームに推奨されます。

  • sequelize:

    sequelize は最も歴史があり、コミュニティが大きい ORM です。安定性を最優先し、豊富なプラグインやドキュメントを必要とする場合に適しています。JavaScript ベースのプロジェクトや、TypeScript を深く使い込まないチームにとって、学習コストが低く導入しやすい選択肢です。

  • objection:

    objection を選ぶべきなのは、knex.js の柔軟性を保ちつつ ORM 機能が必要な場合です。クエリビルダーとしての制御性を重視し、SQL との親和性を高めたいプロジェクトに適しています。TypeScript サポートもあり、複雑なクエリを扱う場合に威力を発揮します。

  • bookshelf:

    bookshelfknex.js に依存する古い ORM であり、現在はメンテナンスモードに入っています。既存のレガシープロジェクトを維持する場合を除き、新規プロジェクトでの採用は避けるべきです。コミュニティの支持は objection に移行しており、長期的なサポートを考えると代替案を検討するのが賢明です。

typeorm のREADME

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.

Features

  • Supports both DataMapper and ActiveRecord (your choice).
  • Entities and columns.
  • Database-specific column types.
  • Entity manager.
  • Repositories and custom repositories.
  • Clean object-relational model.
  • Associations (relations).
  • Eager and lazy relations.
  • Unidirectional, bidirectional, and self-referenced relations.
  • Supports multiple inheritance patterns.
  • Cascades.
  • Indices.
  • Transactions.
  • Migrations and automatic migrations generation.
  • Connection pooling.
  • Replication.
  • Using multiple database instances.
  • Working with multiple database types.
  • Cross-database and cross-schema queries.
  • Elegant-syntax, flexible and powerful QueryBuilder.
  • Left and inner joins.
  • Proper pagination for queries using joins.
  • Query caching.
  • Streaming raw results.
  • Logging.
  • Listeners and subscribers (hooks).
  • Supports closure table pattern.
  • Schema declaration in models or separate configuration files.
  • Supports MySQL / MariaDB / Postgres / CockroachDB / SQLite / Microsoft SQL Server / Oracle / SAP Hana / sql.js.
  • Supports MongoDB NoSQL database.
  • Works in Node.js / Browser / Ionic / Cordova / React Native / NativeScript / Expo / Electron platforms.
  • TypeScript and JavaScript support.
  • ESM and CommonJS support.
  • Produced code is performant, flexible, clean, and maintainable.
  • Follows all possible best practices.
  • CLI.

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()

Samples

Take a look at the samples in sample for examples of usage.

There are a few repositories that you can clone and start with:

Extensions

There are several extensions that simplify working with TypeORM and integrating it with other modules:

Contributing

Learn about contribution here and how to set up your development environment here.

This project exists thanks to all the people who contribute:

Sponsors

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.

Champion

Become a champion sponsor and get premium technical support from our core contributors. Become a champion

Supporter

Support TypeORM's development with a monthly contribution. Become a supporter

Community

Join our community of supporters and help sustain TypeORM. Become a community supporter

Sponsor

Make a one-time or recurring contribution of your choice. Become a sponsor