bookshelf vs mongoose vs sequelize vs waterline
Node.js 環境における ORM/ODM ライブラリの選定ガイド
bookshelfmongoosesequelizewaterline類似パッケージ:

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

bookshelfmongoosesequelizewaterline は、Node.js アプリケーションでデータベース操作を抽象化するためのライブラリです。mongoose は MongoDB 専用の ODM であり、スキーマ定義とドキュメント操作に最適化されています。sequelize は PostgreSQL、MySQL などのリレーショナルデータベース(SQL)をサポートする ORM で、型安全性と機能の豊富さが特徴です。bookshelf は Knex.js ベースの SQL ORM ですが、近年メンテナンス頻度が低下しています。waterline は Sails.js フレームワークのために設計されたデータアクセスレイヤーで、アダプター経由で複数の DB を扱えますが、独自の制約が多く、現代的な開発では採用が慎重になっています。

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

3 年

GitHub Starsランキング

統計詳細

パッケージ
ダウンロード数
Stars
サイズ
Issues
公開日時
ライセンス
bookshelf06,362-2386年前MIT
mongoose027,4722.07 MB18314日前MIT
sequelize030,3522.91 MB1,0231ヶ月前MIT
waterline05,3981.3 MB34-MIT

Node.js ORM/ODM 徹底比較:Bookshelf, Mongoose, Sequelize, Waterline

Node.js でデータベースを扱う際、生 SQL やドライバを直接叩くのではなく、ORM(オブジェクト関係マッピング)や ODM(オブジェクトドキュメントマッピング)を使うのが一般的です。bookshelfmongoosesequelizewaterline はそれぞれ異なる哲学と対象データベースを持っており、選び方を間違えると後々の開発速度や保守性に大きく影響します。

フロントエンドアーキテクトとして、バックエンドのデータ層の特性を理解することは、API デザインや状態管理の方針を決める上で重要です。ここでは、これら 4 つのライブラリの技術的な違いと、実際のコードがどう変わるかを深掘りします。

🗄️ 対象データベース:SQL か NoSQL か

ライブラリを選ぶ最初の基準は、使用するデータベースの種類です。

mongoose は MongoDB 専用です。

  • JSON ライクなドキュメントを扱います。
  • スキーマは柔軟ですが、定義することでバリデーション恩恵を受けられます。
// mongoose: MongoDB 用
const userSchema = new mongoose.Schema({ name: String });
const User = mongoose.model('User', userSchema);
const user = await User.findOne({ name: 'Alice' });

sequelize はリレーショナルデータベース(SQL)専用です。

  • PostgreSQL, MySQL, MariaDB, SQLite, SQL Server をサポートします。
  • テーブル間のリレーションを強力に管理できます。
// sequelize: SQL 用
const User = sequelize.define('User', { name: DataTypes.STRING });
const user = await User.findOne({ where: { name: 'Alice' } });

bookshelf も SQL データベース用です。

  • Knex.js クエリビルダーに依存しています。
  • 複数の SQL データベースに対応しますが、設定は手動寄りです。
// bookshelf: SQL 用 (Knex ベース)
const User = bookshelf.Model.extend({ tableName: 'users' });
const user = await User.where({ name: 'Alice' }).fetch();

waterline はデータベースアグノスティックを謳っていますが、実態はアダプター依存です。

  • MongoDB も SQL も使えますが、クエリ構文は独自のものになります。
  • Sails.js フレームワークとの連携が前提となっています。
// waterline: 汎用 (アダプター依存)
// Sails.js コンテキスト内での記述例
const user = await User.findOne({ name: 'Alice' });

🔗 リレーションとデータ取得:結合の扱い方

複数のテーブルやコレクションにまたがるデータを取得する際、各ライブラリのアプローチは大きく異なります。

sequelizeinclude オプションを使って SQL の JOIN を抽象化します。

  • 事前定義されたアソシエーションに基づいて、ネストされたデータを一度に取得できます。
  • 型定義と整合性を取りやすい構造です。
// sequelize: 関連データを同時に取得
const user = await User.findOne({
  where: { id: 1 },
  include: [{ model: Post, as: 'posts' }]
});
// user.posts が自動的に含まれる

mongoosepopulate メソッドを使います。

  • MongoDB は JOIN をサポートしないため、参照 ID を元に別クエリを発行して結合します。
  • 柔軟ですが、パフォーマンスにはインデックス設計が重要です。
// mongoose: 参照を解決して取得
const user = await User.findById(1).populate('posts');
// posts 配列にドキュメント本体が入る

bookshelfwithRelated を使用します。

  • Knex のクエリを元に、Eager Loading を実現します。
  • リレーションの定義はモデルクラス内で行います。
// bookshelf: 関連データの Eager Loading
const user = await User.where({ id: 1 }).fetch({
  withRelated: ['posts']
});
// user.related('posts') でアクセス

waterlinepopulate メソッドを提供します。

  • 構文はシンプルですが、複雑な結合やネストには限界があります。
  • アダプターの実装次第で動作が異なる可能性があります。
// waterline: 結合取得
const user = await User.findOne({ id: 1 }).populate('posts');
// 結果オブジェクトに posts が付与される

🛠️ メンテナンス状況と将来性

ライブラリの選定において、メンテナンス状況は機能以上に重要です。開発が止まっているライブラリはセキュリティリスクや、新しい Node.js バージョンとの非互換性を招きます。

mongoosesequelize は活発にメンテナンスされています。

  • 定期的にセキュリティパッチが適用され、新しいデータベース機能にも対応しています。
  • TypeScript の型定義も充実しており、現代的な開発環境に適合します。
  • 新規プロジェクトでは、SQL なら sequelize、MongoDB なら mongoose を選ぶのが安全です。

bookshelf はメンテナンスが停滞しています。

  • GitHub でのコミット頻度が极低く、Issues の対応も遅れがちです。
  • 依存している Knex.js は活発ですが、Bookshelf 自体の将来性は不透明です。
  • 新規プロジェクトでの使用は避けるべきです。Knex.js を直接使用するか、sequelize に移行することを強く推奨します。

waterline は Sails.js エコシステムに依存しています。

  • Sails.js を使わない場合、単体での利用はドキュメントが少なく困難です。
  • 独自の実装が多く、標準的な ORM のパターンから外れている部分があります。
  • Sails.js を採用しない限り、選択肢から外れるでしょう。

📝 クエリ構築の柔軟性

複雑な検索条件や集計処理を行う際、ライブラリがどこまで許容するかもポイントです。

sequelize はクエリ構築能力が高いです。

  • Op オペレーターを使って複雑な WHERE 句を構築できます。
  • 生 SQL を混ぜることも容易です。
// sequelize: 複雑な条件
const { Op } = require('sequelize');
const users = await User.findAll({
  where: {
    [Op.or]: [{ age: { [Op.gt]: 20 } }, { role: 'admin' }]
  }
});

mongoose もクエリチェーンが強力です。

  • メソッドチェーンで条件を積み重ねられます。
  • アグリゲーションパイプラインも利用可能です。
// mongoose: クエリチェーン
const users = await User.find({ age: { $gt: 20 } })
  .where('role').equals('admin')
  .exec();

bookshelf は Knex の機能を引き継ぎます。

  • クエリビルダーとしての機能は強力ですが、ORM 層での抽象化が薄れることがあります。
// bookshelf: Knex クエリ活用
const users = await User.query(qb => {
  qb.where('age', '>', 20).orWhere('role', 'admin');
}).fetchAll();

waterline は独自構文に制限されます。

  • 複雑なクエリを書こうとすると、ネイティブクエリを使う必要が出てくることがあります。
  • 学習コストに対して得られる柔軟性は低めです。
// waterline: 制限のあるクエリ
const users = await User.find({
  or: [{ age: { '>': 20 } }, { role: 'admin' }]
});

📊 比較サマリー

特徴mongoosesequelizebookshelfwaterline
DB 種類MongoDB (NoSQL)SQL (RDBMS)SQL (RDBMS)両方 (アダプター)
メンテナンス✅ 活発✅ 活発⚠️ 停滞⚠️ Sails 依存
型サポート✅ 良好 (TS)✅ 優秀 (TS)⚠️ 限定的⚠️ 限定的
学習コスト高 (独自規則)
推奨度 (Mongo 時) (SQL 時) (非推奨) (Sails 以外)

💡 結論:何をすべきか

プロジェクトのデータベース選定がまだであれば、リレーショナルなら PostgreSQL + sequelizeドキュメントストアなら MongoDB + mongoose の組み合わせが最もリスクが少なく、人材も確保しやすいです。

bookshelf は過去に多くのプロジェクトで使われましたが、現在では技術的負債になる可能性が高いです。既存システムを維持する場合を除き、新しい選択リストに入れるべきではありません。

waterline は Sails.js という「フルスタックフレームワーク」の一部として設計されており、Express や Nest.js など他のフレームワークと組み合わせるメリットはほとんどありません。

フロントエンドアーキテクトとしてバックエンド技術を選定する際は、単なる機能比較だけでなく、**「5 年後もメンテナンスされているか」「困った時に情報が見つかるか」**という視点が重要です。その点で mongoosesequelize は信頼できる選択肢です。

選び方: bookshelf vs mongoose vs sequelize vs waterline

  • bookshelf:

    bookshelf は Knex.js クエリビルダーの上に構築されており、SQL データベースを扱う場合に選択されますが、メンテナンスが停滞しているため、新規プロジェクトでの採用は推奨されません。既存のレガシーシステムを保守する場合や、Knex.js との親和性が最優先される場合にのみ検討してください。代わりに sequelizeknex 単体の使用を検討すべきです。

  • mongoose:

    MongoDB を使用する場合は mongoose が事実上の標準です。スキーマ定義、バリデーション、ミドルウェア機能が充実しており、ドキュメント指向データベースの特性を活かした開発が可能です。Node.js との親和性が高く、非同期処理との相性も良いため、MERN スタックなどで広く選ばれています。

  • sequelize:

    リレーショナルデータベース(PostgreSQL, MySQL など)を使用し、型安全性や高度なリレーション管理が必要な場合に sequelize を選択します。Promise ベースの API と TypeScript サポートが充実しており、大規模なエンタープライズアプリケーションに適しています。マイグレーションツールも内蔵されているため、スキーマ管理も一元化できます。

  • waterline:

    waterline は Sails.js フレームワークと密接に結びついており、Sails を使用しないプロジェクトでの単独利用は推奨されません。複数の異なるデータベースを同時に扱う必要がある場合に威力を発揮しますが、クエリのカスタマイズ性が低く、複雑なビジネスロジックには向かないことがあります。新規プロジェクトでは、より汎用性の高い ORM の採用を検討してください。

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.