bookshelf vs objection vs sequelize vs waterline
Node.js 关系型数据库 ORM 选型指南
bookshelfobjectionsequelizewaterline类似的npm包:

Node.js 关系型数据库 ORM 选型指南

这四个库都是 Node.js 生态中用于简化数据库操作的对象关系映射(ORM)工具。sequelize 是功能最全面的选择,支持多种数据库方言。objectionbookshelf 都基于 knex 查询构建器,提供更接近 SQL 的控制力。waterline 则是 Sails.js 框架的默认 ORM,支持多种数据库类型但耦合度较高。对于前端开发者而言,理解这些工具的区别有助于在构建全栈应用或 BFF 层时做出正确的架构决策。

npm下载趋势

3 年

GitHub Stars 排名

统计详情

npm包名称
下载量
Stars
大小
Issues
发布时间
License
bookshelf06,362-2386 年前MIT
objection07,343645 kB1292 年前MIT
sequelize030,3522.91 MB1,0231 个月前MIT
waterline05,3981.3 MB34-MIT

Node.js ORM 深度对比:Sequelize, Objection, Bookshelf, Waterline

对于从前端转向全栈开发的工程师来说,选择合适的数据库工具至关重要。sequelizeobjectionbookshelfwaterline 都是 Node.js 生态中历史悠久的 ORM 库,但它们的设计理念和适用场景差异巨大。本文将深入对比它们的核心用法、架构差异及维护状态,帮助你在实际工程中做出明智选择。

🏗️ 模型定义:配置驱动 vs 类驱动

定义数据模型是 ORM 的第一步。不同库在处理模型结构时有不同的哲学。

sequelize 使用配置对象来定义模型,支持丰富的数据类型和验证规则。

// sequelize: 使用 define 定义模型
const User = sequelize.define('User', {
  firstName: { type: DataTypes.STRING, allowNull: false },
  lastName: { type: DataTypes.STRING }
}, { tableName: 'users' });

objection 使用 ES6 类继承,结构更清晰,适合喜欢面向对象风格的开发者。

// objection: 继承 Model 类
class User extends Model {
  static get tableName() {
    return 'users';
  }
}

bookshelf 同样基于对象扩展,但语法较为传统,依赖 knex 实例。

// bookshelf: 使用 extend 扩展模型
const User = bookshelf.Model.extend({
  tableName: 'users'
});

waterline 通常在 Sails.js 配置文件中定义,耦合度较高。

// waterline: 在模型文件中定义属性
module.exports = {
  attributes: {
    firstName: { type: 'string', required: true },
    lastName: { type: 'string' }
  }
};

🔍 数据查询:链式调用 vs 配置对象

查询数据的语法直接影响代码的可读性和维护性。

sequelize 提供强大的查找配置对象,支持复杂的 include 和 where 条件。

// sequelize: 使用 findAll 查询
const users = await User.findAll({
  where: { lastName: 'Smith' },
  attributes: ['firstName', 'lastName']
});

objection 提供流畅的链式 API,底层直接编译为 Knex 查询。

// objection: 链式查询
const users = await User.query()
  .select('firstName', 'lastName')
  .where('lastName', 'Smith');

bookshelf 类似 Objection,但 API 设计较旧,返回的是集合对象。

// bookshelf: 使用 fetchAll 查询
const users = await User.where({ last_name: 'Smith' }).fetchAll({
  columns: ['first_name', 'last_name']
});

waterline 使用简单的对象语法,类似 MongoDB 风格,但功能有限。

// waterline: 使用 find 方法
const users = await User.find({
  where: { lastName: 'Smith' },
  select: ['firstName', 'lastName']
});

🔗 关系处理:自动关联 vs 手动加载

处理表之间的关系(如一对多、多对多)是 ORM 的核心价值。

sequelize 支持预定义关联,查询时自动加载相关数据。

// sequelize: 定义关联并加载
User.hasMany(Post);
const user = await User.findOne({
  where: { id: 1 },
  include: [Post]
});

objection 使用 relationMappings 定义关系,查询时使用 withGraphFetched

// objection: 定义关系并加载
class User extends Model {
  static get relationMappings() {
    return { posts: { relation: HasManyRelation, modelClass: Post } };
  }
}
const user = await User.query().findById(1).withGraphFetched('posts');

bookshelf 需要在模型上定义关系方法,加载时需显式调用。

// bookshelf: 定义关系方法
const User = bookshelf.Model.extend({
  tableName: 'users',
  posts: function() { return this.hasMany(Post); }
});
const user = await User.where({ id: 1 }).fetch({ withRelated: ['posts'] });

waterline 通过属性定义关联,自动处理关联查询。

// waterline: 属性定义关联
module.exports = {
  attributes: {
    posts: { collection: 'post', via: 'userId' }
  }
};
const user = await User.findOne(1).populate('posts');

⚠️ 维护状态与生态健康

选择开源库时,维护状态是长期稳定性的关键。

sequelize 目前维护非常活跃,社区庞大,文档完善。它是生产环境最安全的选择之一,适合长期项目。

objection 维护状态良好,作为 knex 的上层封装,它受益于 knex 的稳定性。适合需要 SQL 控制力的团队。

bookshelf 社区活跃度已显著下降。虽然仍可使用,但新功能开发已停滞。官方和社区普遍建议迁移至 objection

waterline 主要服务于 Sails.js 框架。作为独立库使用时,其更新频率较低,且受限于框架的设计决策。非 Sails 项目应避免使用。

📊 核心特性对比表

特性sequelizeobjectionbookshelfwaterline
底层基础自研查询层基于 knex基于 knex自研适配器
数据库支持广泛 (SQL)广泛 (SQL)广泛 (SQL)广泛 (SQL/NoSQL)
查询风格配置对象链式调用链式调用配置对象
迁移工具内置 (CLI)需配合 knex需配合 knex内置 (Sails)
维护状态✅ 活跃✅ 活跃⚠️ 维护模式⚠️ 框架绑定
学习曲线低 (限 Sails)

💡 最终建议

sequelize 是全能型选手 🏆 — 适合需要快速开发、支持多种数据库且不希望处理底层 SQL 细节的团队。它是大多数企业级 Node.js 应用的首选。

objection 是专家型工具 🛠️ — 适合已经熟悉 knex 或需要对 SQL 查询有更高控制力的开发者。它在性能和灵活性之间取得了很好的平衡。

bookshelfwaterline 属于特定历史时期的产物 🕰️ — 除非你正在维护旧系统或深度绑定 Sails.js 框架,否则在新项目中不建议引入。现代 Node.js 开发更倾向于 sequelizeobjection

总结:对于前端转型全栈的开发者,如果追求稳妥和功能丰富,选 sequelize;如果追求轻量和对 SQL 的掌控,选 objection。避免在新项目中使用 bookshelfwaterline,以减少未来的技术债务。

如何选择: bookshelf vs objection vs sequelize vs waterline

  • bookshelf:

    仅当维护基于 knex 的旧项目时考虑 bookshelf。新项目中不建议使用,因为社区活跃度已大幅下降,objection 通常是更好的替代方案。

  • objection:

    如果您已经熟悉 knex 或需要更灵活的 SQL 控制能力,请选择 objection。它比 sequelize 更轻量,专注于关系映射而不隐藏 SQL 细节,适合对性能有精细要求的团队。

  • sequelize:

    如果您需要支持多种数据库(如 PostgreSQL、MySQL、SQLite 等)且希望 ORM 处理大部分底层细节,请选择 sequelize。它适合企业级应用,功能丰富但相对重量级,学习曲线较陡。

  • waterline:

    仅在使用 Sails.js 框架时才选择 waterline。对于独立的 Node.js 服务或现代全栈架构,它的耦合度太高且灵活性不足,不建议作为独立 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.