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 が頭一つ抜けています。
bookshelf は knex.js に依存する古い ORM であり、現在はメンテナンスモードに入っています。既存のレガシープロジェクトを維持する場合を除き、新規プロジェクトでの採用は避けるべきです。コミュニティの支持は objection に移行しており、長期的なサポートを考えると代替案を検討するのが賢明です。
objection を選ぶべきなのは、knex.js の柔軟性を保ちつつ ORM 機能が必要な場合です。クエリビルダーとしての制御性を重視し、SQL との親和性を高めたいプロジェクトに適しています。TypeScript サポートもあり、複雑なクエリを扱う場合に威力を発揮します。
sequelize は最も歴史があり、コミュニティが大きい ORM です。安定性を最優先し、豊富なプラグインやドキュメントを必要とする場合に適しています。JavaScript ベースのプロジェクトや、TypeScript を深く使い込まないチームにとって、学習コストが低く導入しやすい選択肢です。
typeorm を選ぶべきは、TypeScript を-first で開発するプロジェクトです。デコレータを使った定義は型安全性が高く、NestJS などのフレームワークとの相性が抜群です。エンティティベースの設計が好みで、コンパイル時のエラー検出を重視するチームに推奨されます。
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.
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.
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', {
// ...
})
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)
})
.set() on a model.Model, adding timestamps, attribute validation and some native CRUD methods.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.
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.
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.
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.
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.
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)
})
See the CONTRIBUTING document on GitHub.
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.
We found the following projects using Bookshelf, but there can be more: