bookshelf vs mongoose vs sequelize vs typeorm
Node.js ORM Libraries
bookshelfmongoosesequelizetypeorm类似的npm包:

Node.js ORM Libraries

Node.js ORM(对象关系映射)库用于简化与数据库的交互,使开发者能够使用JavaScript对象而不是SQL查询来操作数据库。ORM库提供了一种抽象层,使得数据模型与数据库表之间的映射变得简单,允许开发者专注于业务逻辑而不是底层数据访问细节。每个库都有其独特的设计理念和功能,适用于不同的使用场景和需求。

npm下载趋势

3 年

GitHub Stars 排名

统计详情

npm包名称
下载量
Stars
大小
Issues
发布时间
License
bookshelf59,3036,368-2386 年前MIT
mongoose027,4532.04 MB19512 天前MIT
sequelize030,3422.91 MB1,0081 年前MIT
typeorm036,34320.8 MB5043 个月前MIT

功能对比: bookshelf vs mongoose vs sequelize vs typeorm

数据库支持

  • bookshelf:

    Bookshelf支持多种SQL数据库,如PostgreSQL、MySQL和SQLite。它使用Knex.js作为查询构建器,允许开发者使用SQL语法进行复杂查询。

  • mongoose:

    Mongoose专为MongoDB设计,提供了强大的数据建模和验证功能,能够轻松处理文档和集合。

  • sequelize:

    Sequelize支持多种SQL数据库,包括PostgreSQL、MySQL、MariaDB和SQLite,提供丰富的查询功能和关系管理。

  • typeorm:

    TypeORM支持多种SQL和NoSQL数据库,包括PostgreSQL、MySQL、SQLite和MongoDB,提供灵活的模型定义和查询功能。

数据模型

  • bookshelf:

    Bookshelf允许开发者使用JavaScript对象定义模型,支持继承和关系定义。它的模型定义简单直观,适合快速开发。

  • mongoose:

    Mongoose提供Schema定义,允许开发者为数据模型定义字段类型、验证规则和默认值,确保数据的一致性和完整性。

  • sequelize:

    Sequelize支持丰富的模型定义,包括字段类型、验证、钩子和关系,能够轻松管理复杂的数据结构。

  • typeorm:

    TypeORM支持使用装饰器定义模型,提供强类型支持,适合TypeScript开发者。它支持Active Record和Data Mapper两种模式,灵活性高。

查询构建

  • bookshelf:

    Bookshelf使用Knex.js作为查询构建器,允许开发者使用链式调用构建复杂查询,支持原生SQL查询。

  • mongoose:

    Mongoose提供了丰富的查询API,支持链式调用和聚合操作,能够轻松处理复杂的查询需求。

  • sequelize:

    Sequelize提供强大的查询构建功能,支持链式调用、事务、关联查询和聚合函数,适合复杂的数据库操作。

  • typeorm:

    TypeORM支持使用QueryBuilder构建复杂查询,提供灵活的查询选项和参数化查询,适合需要动态查询的应用。

学习曲线

  • bookshelf:

    Bookshelf的学习曲线相对较平缓,适合需要快速上手的开发者。其API简单易懂,适合小型项目和快速开发。

  • mongoose:

    Mongoose的学习曲线稍陡,尤其是在Schema定义和数据验证方面,但其强大的功能使得处理复杂数据结构变得容易。

  • sequelize:

    Sequelize的学习曲线适中,提供了丰富的功能和文档,适合需要全面功能的开发者。

  • typeorm:

    TypeORM的学习曲线较陡,尤其是对于不熟悉TypeScript的开发者,但其类型安全和灵活性使得它在大型项目中非常有用。

社区支持

  • bookshelf:

    Bookshelf的社区相对较小,但由于其基于Knex.js,开发者可以利用Knex.js的文档和社区资源。

  • mongoose:

    Mongoose拥有活跃的社区和丰富的文档,开发者可以轻松找到解决方案和示例。

  • sequelize:

    Sequelize是一个成熟的ORM,拥有广泛的社区支持和大量的学习资源,适合新手和经验丰富的开发者。

  • typeorm:

    TypeORM的社区正在快速增长,提供了丰富的文档和示例,适合希望使用TypeScript的开发者。

如何选择: bookshelf vs mongoose vs sequelize vs typeorm

  • bookshelf:

    选择Bookshelf如果你需要一个轻量级的ORM,支持多种数据库,并且希望使用Promise和Knex.js的查询构建器。它适合需要灵活性和可扩展性的项目。

  • mongoose:

    选择Mongoose如果你正在使用MongoDB,并且需要一个功能强大的数据建模工具。Mongoose提供了丰富的Schema定义和验证功能,适合需要复杂数据结构的应用。

  • sequelize:

    选择Sequelize如果你需要一个功能全面的ORM,支持多种SQL数据库,并且希望使用Promise和async/await语法。Sequelize提供了强大的模型定义和关系管理功能,适合大型应用。

  • typeorm:

    选择TypeORM如果你希望使用TypeScript,并且需要一个支持Active Record和Data Mapper模式的ORM。TypeORM适合需要高度类型安全和灵活性的项目。

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.