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

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

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

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

3 年

GitHub Starsランキング

統計詳細

パッケージ
ダウンロード数
Stars
サイズ
Issues
公開日時
ライセンス
bookshelf06,361-2386年前MIT
objection07,344645 kB1292年前MIT
sequelize030,3522.91 MB1,0231ヶ月前MIT
typeorm036,44320.8 MB5285ヶ月前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 が頭一つ抜けています。

選び方: bookshelf vs objection vs sequelize vs typeorm

  • bookshelf:

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

  • objection:

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

  • sequelize:

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

  • typeorm:

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

bookshelf のREADME

bookshelf.js

NPM Version Build Status Dependency Status devDependency Status

Bookshelf is a JavaScript ORM for Node.js, built on the Knex SQL query builder. It features both Promise-based and traditional callback interfaces, transaction support, eager/nested-eager relation loading, polymorphic associations, and support for one-to-one, one-to-many, and many-to-many relations.

It is designed to work with PostgreSQL, MySQL, and SQLite3.

Website and documentation. The project is hosted on GitHub, and has a comprehensive test suite.

Introduction

Bookshelf aims to provide a simple library for common tasks when querying databases in JavaScript, and forming relations between these objects, taking a lot of ideas from the Data Mapper Pattern.

With a concise, literate codebase, Bookshelf is simple to read, understand, and extend. It doesn't force you to use any specific validation scheme, and provides flexible, efficient relation/nested-relation loading and first-class transaction support.

It's a lean object-relational mapper, allowing you to drop down to the raw Knex interface whenever you need a custom query that doesn't quite fit with the stock conventions.

Installation

You'll need to install a copy of Knex, and either mysql, pg, or sqlite3 from npm.

$ npm install knex
$ npm install bookshelf

# Then add one of the following:
$ npm install pg
$ npm install mysql
$ npm install sqlite3

The Bookshelf library is initialized by passing an initialized Knex client instance. The Knex documentation provides a number of examples for different databases.

// Setting up the database connection
const knex = require('knex')({
  client: 'mysql',
  connection: {
    host     : '127.0.0.1',
    user     : 'your_database_user',
    password : 'your_database_password',
    database : 'myapp_test',
    charset  : 'utf8'
  }
})
const bookshelf = require('bookshelf')(knex)

// Defining models
const User = bookshelf.model('User', {
  tableName: 'users'
})

This initialization should likely only ever happen once in your application. As it creates a connection pool for the current database, you should use the bookshelf instance returned throughout your library. You'll need to store this instance created by the initialize somewhere in the application so you can reference it. A common pattern to follow is to initialize the client in a module so you can easily reference it later:

// In a file named, e.g. bookshelf.js
const knex = require('knex')(dbConfig)
module.exports = require('bookshelf')(knex)

// elsewhere, to use the bookshelf client:
const bookshelf = require('./bookshelf')

const Post = bookshelf.model('Post', {
  // ...
})

Examples

Here is an example to get you started:

const knex = require('knex')({
  client: 'mysql',
  connection: process.env.MYSQL_DATABASE_CONNECTION
})
const bookshelf = require('bookshelf')(knex)

const User = bookshelf.model('User', {
  tableName: 'users',
  posts() {
    return this.hasMany(Posts)
  }
})

const Post = bookshelf.model('Post', {
  tableName: 'posts',
  tags() {
    return this.belongsToMany(Tag)
  }
})

const Tag = bookshelf.model('Tag', {
  tableName: 'tags'
})

new User({id: 1}).fetch({withRelated: ['posts.tags']}).then((user) => {
  console.log(user.related('posts').toJSON())
}).catch((error) => {
  console.error(error)
})

Official Plugins

  • Virtuals: Define virtual properties on your model to compute new values.
  • Case Converter: Handles the conversion between the database's snake_cased and a model's camelCased properties automatically.
  • Processor: Allows defining custom processor functions that handle transformation of values whenever they are .set() on a model.

Community plugins

  • bookshelf-cascade-delete - Cascade delete related models on destroy.
  • bookshelf-json-columns - Parse and stringify JSON columns on save and fetch instead of manually define hooks for each model (PostgreSQL and SQLite).
  • bookshelf-mask - Similar to the functionality of the {@link Model#visible} attribute but supporting multiple scopes, masking models and collections using the json-mask API.
  • bookshelf-schema - A plugin for handling fields, relations, scopes and more.
  • bookshelf-signals - A plugin that translates Bookshelf events to a central hub.
  • bookshelf-paranoia - Protect your database from data loss by soft deleting your rows.
  • bookshelf-uuid - Automatically generates UUIDs for your models.
  • bookshelf-modelbase - An alternative to extend Model, adding timestamps, attribute validation and some native CRUD methods.
  • bookshelf-advanced-serialization - A more powerful visibility plugin, supporting serializing models and collections according to access permissions, application context, and after ensuring relations have been loaded.
  • bookshelf-plugin-mode - Plugin inspired by the functionality of the {@link Model#visible} attribute, allowing to specify different modes with corresponding visible/hidden fields of model.
  • bookshelf-secure-password - A plugin for easily securing passwords using bcrypt.
  • bookshelf-default-select - Enables default column selection for models. Inspired by the functionality of the {@link Model#visible} attribute, but operates on the database level.
  • bookshelf-ez-fetch - Convenient fetching methods which allow for compact filtering, relation selection and error handling.
  • bookshelf-manager - Model & Collection manager to make it easy to create & save deep, nested JSON structures from API requests.

Support

Have questions about the library? Come join us in the #bookshelf freenode IRC channel for support on knex.js and bookshelf.js, or post an issue on Stack Overflow.

Contributing

If you want to contribute to Bookshelf you'll usually want to report an issue or submit a pull-request. For this purpose the online repository is available on GitHub.

For further help setting up your local development environment or learning how you can contribute to Bookshelf you should read the Contributing document available on GitHub.

F.A.Q.

Can I use standard node.js style callbacks?

Yes, you can call .asCallback(function(err, resp) { on any database operation method and use the standard (err, result) style callback interface if you prefer.

My relations don't seem to be loading, what's up?

Make sure to check that the type is correct for the initial parameters passed to the initial model being fetched. For example new Model({id: '1'}).load([relations...]) will not return the same as new Model({id: 1}).load([relations...]) - notice that the id is a string in one case and a number in the other. This can be a common mistake if retrieving the id from a url parameter.

This is only an issue if you're eager loading data with load without first fetching the original model. new Model({id: '1'}).fetch({withRelated: [relations...]}) should work just fine.

My process won't exit after my script is finished, why?

The issue here is that Knex, the database abstraction layer used by Bookshelf, uses connection pooling and thus keeps the database connection open. If you want your process to exit after your script has finished, you will have to call .destroy(cb) on the knex property of your Bookshelf instance or on the Knex instance passed during initialization. More information about connection pooling can be found over at the Knex docs.

How do I debug?

If you pass debug: true in the options object to your knex initialize call, you can see all of the query calls being made. You can also pass that same option to all methods that access the database, like model.fetch() or model.destroy(). Examples:

// Turning on debug mode for all queries
const knex = require('knex')({
  debug: true,
  client: 'mysql',
  connection: process.env.MYSQL_DATABASE_CONNECTION
})
const bookshelf = require('bookshelf')(knex)

// Debugging a single query
new User({id: 1}).fetch({debug: true, withRelated: ['posts.tags']}).then(user => {
  // ...
})

Sometimes you need to dive a bit further into the various calls and see what all is going on behind the scenes. You can use node-inspector, which allows you to debug code with debugger statements like you would in the browser.

Bookshelf uses its own copy of the bluebird Promise library. You can read up here for more on debugging Promises.

Adding the following block at the start of your application code will catch any errors not otherwise caught in the normal Promise chain handlers, which is very helpful in debugging:

process.stderr.on('data', (data) => {
  console.log(data)
})

How do I run the test suite?

See the CONTRIBUTING document on GitHub.

Can I use Bookshelf outside of Node.js?

While it primarily targets Node.js, all dependencies are browser compatible, and it could be adapted to work with other javascript environments supporting a sqlite3 database, by providing a custom Knex adapter. No such adapter exists though.

Which open-source projects are using Bookshelf?

We found the following projects using Bookshelf, but there can be more:

  • Ghost (A blogging platform) uses bookshelf. [Link]
  • Soapee (Soap Making Community and Resources) uses bookshelf. [Link]
  • NodeZA (Node.js social platform for developers in South Africa) uses bookshelf. [Link]
  • Sunday Cook (A social cooking event platform) uses bookshelf. [Link]
  • FlyptoX (Open-source Node.js cryptocurrency exchange) uses bookshelf. [Link]
  • And of course, everything on here use bookshelf too.