bookshelf vs knex vs pg-promise vs sequelize
Node.js ORM Libraries
bookshelfknexpg-promisesequelizeSimilar Packages:

Node.js ORM Libraries

Node.js ORM Libraries are tools that help developers interact with databases using object-oriented programming principles. They provide an abstraction layer over the database, allowing developers to perform CRUD (Create, Read, Update, Delete) operations using JavaScript objects instead of writing raw SQL queries. This approach improves code readability, maintainability, and security by preventing SQL injection attacks. Popular Node.js ORM libraries include Sequelize, TypeORM, and Mongoose, each offering unique features and capabilities for different types of databases and applications.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
bookshelf06,355-2386 years agoMIT
knex020,268916 kB7078 days agoMIT
pg-promise03,552411 kB02 months agoMIT
sequelize030,3462.91 MB1,0282 months agoMIT

Feature Comparison: bookshelf vs knex vs pg-promise vs sequelize

Database Support

  • bookshelf:

    bookshelf supports multiple databases through Knex.js, including PostgreSQL, MySQL, and SQLite. However, it does not provide native support for NoSQL databases.

  • knex:

    knex supports a wide range of SQL databases, including PostgreSQL, MySQL, SQLite, and Oracle. It is highly versatile and can be used with any SQL-compliant database.

  • pg-promise:

    pg-promise is specifically designed for PostgreSQL, offering deep integration with PostgreSQL features and capabilities. It is not suitable for other database types.

  • sequelize:

    sequelize supports multiple SQL databases, including PostgreSQL, MySQL, MariaDB, SQLite, and Microsoft SQL Server. It provides a unified API for working with different database dialects.

Query Building

  • bookshelf:

    bookshelf provides a simple and intuitive query building interface, leveraging Knex.js under the hood. It allows for easy creation of complex queries, but it is not as flexible as Knex for low-level query manipulation.

  • knex:

    knex offers a powerful and flexible query building API that allows for programmatic construction of SQL queries. It supports chaining, raw queries, and provides fine-grained control over the generated SQL.

  • pg-promise:

    pg-promise allows for both programmatic query building and raw SQL execution. It provides a flexible API for creating dynamic queries, but it does not include a built-in query builder like Knex.

  • sequelize:

    sequelize provides a high-level query API that abstracts away much of the SQL complexity. It supports chaining, raw queries, and includes features like pagination and filtering out of the box.

Migrations

  • bookshelf:

    bookshelf does not include a built-in migration tool, but it can be easily integrated with Knex.js migrations, allowing for schema management and versioning.

  • knex:

    knex includes a powerful migration and seeding tool as part of the package. It provides a CLI for creating and running migrations, making it easy to manage database schema changes.

  • pg-promise:

    pg-promise does not provide built-in migration tools, but it can be integrated with third-party migration libraries like node-pg-migrate or db-migrate for schema management.

  • sequelize:

    sequelize includes a built-in migration and seeding system, complete with a CLI for creating and running migrations. It also supports migration rollback and versioning.

Associations

  • bookshelf:

    bookshelf supports various types of associations, including one-to-one, one-to-many, and many-to-many. It provides a simple API for defining and working with relationships between models.

  • knex:

    knex does not provide built-in support for associations, as it is primarily a query builder. However, associations can be implemented manually in the application logic or by using additional libraries.

  • pg-promise:

    pg-promise does not have built-in support for associations, but it allows for manual implementation of relationships in the database and application code. It provides flexibility for handling related data as needed.

  • sequelize:

    sequelize provides robust support for associations, including one-to-one, one-to-many, and many-to-many relationships. It offers a rich API for defining and managing associations, including eager and lazy loading.

Ease of Use: Code Examples

  • bookshelf:

    bookshelf Example:

    const Bookshelf = require('bookshelf');
    const knex = require('knex')({
      client: 'pg',
      connection: {
        host: 'localhost',
        user: 'user',
        password: 'password',
        database: 'mydb'
      }
    });
    
    const bookshelf = Bookshelf(knex);
    
    // Define a model
    const User = bookshelf.model('User', {
      tableName: 'users',
    });
    
    // Fetch a user
    User.where({ id: 1 }).fetch().then(user => {
      console.log(user.toJSON());
    });
    
  • knex:

    knex Example:

    const knex = require('knex')({
      client: 'pg',
      connection: {
        host: 'localhost',
        user: 'user',
        password: 'password',
        database: 'mydb'
      }
    });
    
    // Query example
    knex('users').where({ id: 1 }).first().then(user => {
      console.log(user);
    });
    
  • pg-promise:

    pg-promise Example:

    const pgp = require('pg-promise')();
    const db = pgp({
      host: 'localhost',
      user: 'user',
      password: 'password',
      database: 'mydb'
    });
    
    // Query example
    db.one('SELECT * FROM users WHERE id = $1', 1)
      .then(user => {
        console.log(user);
      });
    
  • sequelize:

    sequelize Example:

    const { Sequelize, DataTypes } = require('sequelize');
    const sequelize = new Sequelize('postgres://user:password@localhost:5432/mydb');
    
    // Define a model
    const User = sequelize.define('User', {
      name: { type: DataTypes.STRING },
      email: { type: DataTypes.STRING },
    });
    
    // Fetch a user
    User.findByPk(1).then(user => {
      console.log(user.toJSON());
    });
    

How to Choose: bookshelf vs knex vs pg-promise vs sequelize

  • bookshelf:

    Choose bookshelf if you prefer a lightweight ORM that follows the Active Record pattern and provides a simple API for working with related data. It is built on top of Knex.js, making it a good choice if you are already using Knex for query building.

  • knex:

    Choose knex if you need a flexible and powerful SQL query builder that supports multiple database dialects. It is not an ORM but provides a robust foundation for building complex queries programmatically while allowing for raw SQL when needed.

  • pg-promise:

    Choose pg-promise if you are working specifically with PostgreSQL and need a feature-rich library that supports advanced PostgreSQL features, transactions, and query formatting. It is highly customizable and provides excellent performance for PostgreSQL applications.

  • sequelize:

    Choose sequelize if you need a full-featured ORM with support for multiple database dialects, including PostgreSQL, MySQL, and SQLite. It offers a rich set of features, including migrations, associations, and a powerful query API, making it suitable for complex applications.

README for bookshelf

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.