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

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
公開日時
ライセンス
mongoose4,348,34527,4622.05 MB1995日前MIT
sequelize2,618,20330,3492.91 MB1,0111日前MIT
bookshelf57,1946,363-2386年前MIT
waterline28,5185,4081.3 MB33-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 は信頼できる選択肢です。

選び方: mongoose vs sequelize vs bookshelf vs waterline

  • mongoose:

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

  • sequelize:

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

  • bookshelf:

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

  • waterline:

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

mongoose のREADME

Mongoose

Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. Mongoose supports Node.js and Deno (alpha).

Build Status NPM version Deno version Deno popularity

npm

Documentation

The official documentation website is mongoosejs.com.

Mongoose 9.0.0 was released on November 21, 2025. You can find more details on backwards breaking changes in 9.0.0 on our docs site.

Support

Plugins

Check out the plugins search site to see hundreds of related modules from the community. Next, learn how to write your own plugin from the docs or this blog post.

Contributors

Pull requests are always welcome! Please base pull requests against the master branch and follow the contributing guide.

If your pull requests makes documentation changes, please do not modify any .html files. The .html files are compiled code, so please make your changes in docs/*.pug, lib/*.js, or test/docs/*.js.

View all 400+ contributors.

Installation

First install Node.js and MongoDB. Then:

Then install the mongoose package using your preferred package manager:

Using npm

npm install mongoose

Using pnpm

pnpm add mongoose

Using Yarn

yarn add mongoose

Using Bun

bun add mongoose

Mongoose 6.8.0 also includes alpha support for Deno.

Importing

// Using Node.js `require()`
const mongoose = require('mongoose');

// Using ES6 imports
import mongoose from 'mongoose';

Or, using Deno's createRequire() for CommonJS support as follows.

import { createRequire } from 'https://deno.land/std@0.177.0/node/module.ts';
const require = createRequire(import.meta.url);

const mongoose = require('mongoose');

mongoose.connect('mongodb://127.0.0.1:27017/test')
  .then(() => console.log('Connected!'));

You can then run the above script using the following.

deno run --allow-net --allow-read --allow-sys --allow-env mongoose-test.js

Mongoose for Enterprise

Available as part of the Tidelift Subscription

The maintainers of mongoose and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.

Overview

Connecting to MongoDB

First, we need to define a connection. If your app uses only one database, you should use mongoose.connect. If you need to create additional connections, use mongoose.createConnection.

Both connect and createConnection take a mongodb:// URI, or the parameters host, database, port, options.

await mongoose.connect('mongodb://127.0.0.1/my_database');

Once connected, the open event is fired on the Connection instance. If you're using mongoose.connect, the Connection is mongoose.connection. Otherwise, mongoose.createConnection return value is a Connection.

Note: If the local connection fails then try using 127.0.0.1 instead of localhost. Sometimes issues may arise when the local hostname has been changed.

Important! Mongoose buffers all the commands until it's connected to the database. This means that you don't have to wait until it connects to MongoDB in order to define models, run queries, etc.

Defining a Model

Models are defined through the Schema interface.

const Schema = mongoose.Schema;
const ObjectId = Schema.ObjectId;

const BlogPost = new Schema({
  author: ObjectId,
  title: String,
  body: String,
  date: Date
});

Aside from defining the structure of your documents and the types of data you're storing, a Schema handles the definition of:

The following example shows some of these features:

const Comment = new Schema({
  name: { type: String, default: 'hahaha' },
  age: { type: Number, min: 18, index: true },
  bio: { type: String, match: /[a-z]/ },
  date: { type: Date, default: Date.now },
  buff: Buffer
});

// a setter
Comment.path('name').set(function(v) {
  return capitalize(v);
});

// middleware
Comment.pre('save', function(next) {
  notify(this.get('email'));
  next();
});

Take a look at the example in examples/schema/schema.js for an end-to-end example of a typical setup.

Accessing a Model

Once we define a model through mongoose.model('ModelName', mySchema), we can access it through the same function

const MyModel = mongoose.model('ModelName');

Or just do it all at once

const MyModel = mongoose.model('ModelName', mySchema);

The first argument is the singular name of the collection your model is for. Mongoose automatically looks for the plural version of your model name. For example, if you use

const MyModel = mongoose.model('Ticket', mySchema);

Then MyModel will use the tickets collection, not the ticket collection. For more details read the model docs.

Once we have our model, we can then instantiate it, and save it:

const instance = new MyModel();
instance.my.key = 'hello';
await instance.save();

Or we can find documents from the same collection

await MyModel.find({});

You can also findOne, findById, update, etc.

const instance = await MyModel.findOne({ /* ... */ });
console.log(instance.my.key); // 'hello'

For more details check out the docs.

Important! If you opened a separate connection using mongoose.createConnection() but attempt to access the model through mongoose.model('ModelName') it will not work as expected since it is not hooked up to an active db connection. In this case access your model through the connection you created:

const conn = mongoose.createConnection('your connection string');
const MyModel = conn.model('ModelName', schema);
const m = new MyModel();
await m.save(); // works

vs

const conn = mongoose.createConnection('your connection string');
const MyModel = mongoose.model('ModelName', schema);
const m = new MyModel();
await m.save(); // does not work b/c the default connection object was never connected

Embedded Documents

In the first example snippet, we defined a key in the Schema that looks like:

comments: [Comment]

Where Comment is a Schema we created. This means that creating embedded documents is as simple as:

// retrieve my model
const BlogPost = mongoose.model('BlogPost');

// create a blog post
const post = new BlogPost();

// create a comment
post.comments.push({ title: 'My comment' });

await post.save();

The same goes for removing them:

const post = await BlogPost.findById(myId);
post.comments[0].deleteOne();
await post.save();

Embedded documents enjoy all the same features as your models. Defaults, validators, middleware.

Middleware

See the docs page.

Intercepting and mutating method arguments

You can intercept method arguments via middleware.

For example, this would allow you to broadcast changes about your Documents every time someone sets a path in your Document to a new value:

schema.pre('set', function(next, path, val, typel) {
  // `this` is the current Document
  this.emit('set', path, val);

  // Pass control to the next pre
  next();
});

Moreover, you can mutate the incoming method arguments so that subsequent middleware see different values for those arguments. To do so, just pass the new values to next:

schema.pre(method, function firstPre(next, methodArg1, methodArg2) {
  // Mutate methodArg1
  next('altered-' + methodArg1.toString(), methodArg2);
});

// pre declaration is chainable
schema.pre(method, function secondPre(next, methodArg1, methodArg2) {
  console.log(methodArg1);
  // => 'altered-originalValOfMethodArg1'

  console.log(methodArg2);
  // => 'originalValOfMethodArg2'

  // Passing no arguments to `next` automatically passes along the current argument values
  // i.e., the following `next()` is equivalent to `next(methodArg1, methodArg2)`
  // and also equivalent to, with the example method arg
  // values, `next('altered-originalValOfMethodArg1', 'originalValOfMethodArg2')`
  next();
});

Schema gotcha

type, when used in a schema has special meaning within Mongoose. If your schema requires using type as a nested property you must use object notation:

new Schema({
  broken: { type: Boolean },
  asset: {
    name: String,
    type: String // uh oh, it broke. asset will be interpreted as String
  }
});

new Schema({
  works: { type: Boolean },
  asset: {
    name: String,
    type: { type: String } // works. asset is an object with a type property
  }
});

Driver Access

Mongoose is built on top of the official MongoDB Node.js driver. Each mongoose model keeps a reference to a native MongoDB driver collection. The collection object can be accessed using YourModel.collection. However, using the collection object directly bypasses all mongoose features, including hooks, validation, etc. The one notable exception that YourModel.collection still buffers commands. As such, YourModel.collection.find() will not return a cursor.

API Docs

Mongoose API documentation, generated using dox and acquit.

Related Projects

MongoDB Runners

Unofficial CLIs

Data Seeding

Express Session Stores

License

Copyright (c) 2010 LearnBoost <dev@learnboost.com>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.