bookshelf vs mongoose vs sequelize vs typeorm
Node.js ORM Libraries
bookshelfmongoosesequelizetypeormSimilar Packages:

Node.js ORM Libraries

Node.js ORM (Object-Relational Mapping) libraries provide a way to interact with databases using JavaScript objects instead of SQL queries. They abstract the database interactions, allowing developers to work with data in a more intuitive way. Each of these libraries has its own strengths and use cases, catering to different types of applications and developer preferences. Using an ORM can significantly speed up development time, enforce data integrity, and simplify database migrations, making it easier to manage complex data relationships and operations within Node.js applications.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
bookshelf06,368-2386 years agoMIT
mongoose027,4532.04 MB19512 days agoMIT
sequelize030,3422.91 MB1,008a year agoMIT
typeorm036,34320.8 MB5043 months agoMIT

Feature Comparison: bookshelf vs mongoose vs sequelize vs typeorm

Database Support

  • bookshelf:

    Bookshelf is designed specifically for SQL databases and works with any database supported by Knex.js, such as PostgreSQL, MySQL, and SQLite. It provides a simple and intuitive interface for defining models and relationships, making it easy to interact with relational data.

  • mongoose:

    Mongoose is tailored for MongoDB, providing a schema-based solution that allows developers to define models with strict structures and validations. It leverages MongoDB's document-oriented nature, making it ideal for applications that require a flexible schema.

  • sequelize:

    Sequelize supports multiple SQL dialects, including PostgreSQL, MySQL, SQLite, and MSSQL. It offers a consistent API across different databases, allowing developers to switch databases with minimal changes to their codebase.

  • typeorm:

    TypeORM supports both SQL (PostgreSQL, MySQL, MariaDB, SQLite, MSSQL) and NoSQL databases (MongoDB). This versatility allows developers to choose the best database for their application needs while maintaining a consistent API.

Learning Curve

  • bookshelf:

    Bookshelf has a moderate learning curve, especially for developers familiar with Knex.js. Its straightforward API makes it easy to get started, but understanding its relationship management features may require some time.

  • mongoose:

    Mongoose has a steeper learning curve due to its schema-based approach and extensive feature set. Developers need to understand how to define schemas, validations, and middleware, which can be complex for newcomers.

  • sequelize:

    Sequelize has a comprehensive API that may be overwhelming for beginners. However, its extensive documentation and community support can help ease the learning process. Understanding its features like associations and migrations is crucial for effective usage.

  • typeorm:

    TypeORM is designed with TypeScript in mind, which can make it easier for TypeScript developers to adopt. However, its advanced features and decorators may require a deeper understanding of TypeScript concepts, leading to a moderate learning curve.

Extensibility

  • bookshelf:

    Bookshelf is extensible through plugins, allowing developers to add custom functionalities or modify existing behaviors. This flexibility makes it suitable for projects that require specific features not provided out of the box.

  • mongoose:

    Mongoose supports middleware and custom methods, enabling developers to extend the functionality of their models easily. This extensibility is beneficial for applications that require complex data manipulation or validation logic.

  • sequelize:

    Sequelize is highly extensible, allowing developers to create custom model methods, scopes, and hooks. This flexibility makes it a powerful choice for applications with unique data handling requirements.

  • typeorm:

    TypeORM offers a rich set of decorators and hooks that allow developers to customize their entities and repositories. This extensibility is particularly useful for TypeScript applications that require advanced data management features.

Performance

  • bookshelf:

    Bookshelf's performance is generally good for small to medium-sized applications. However, as the complexity of queries increases, performance may be impacted, especially if not optimized properly.

  • mongoose:

    Mongoose is optimized for MongoDB and can handle large datasets efficiently. However, performance can be affected by the complexity of schemas and the use of middleware, so careful design is essential.

  • sequelize:

    Sequelize provides good performance for most applications, but complex queries and large datasets may require optimization techniques such as eager loading or query caching to maintain efficiency.

  • typeorm:

    TypeORM is designed to be performant, especially in TypeScript applications. It supports lazy loading and efficient query building, but performance can vary depending on the complexity of the data model and the underlying database.

Community and Documentation

  • bookshelf:

    Bookshelf has a smaller community compared to some other ORMs, but it is well-documented and provides a clear API reference. The community support is decent, but finding solutions for specific issues may take more time.

  • mongoose:

    Mongoose has a large and active community, with extensive documentation and numerous tutorials available. This makes it easier for developers to find help and resources when needed, enhancing the overall development experience.

  • sequelize:

    Sequelize boasts a large community and comprehensive documentation, making it one of the most popular ORMs for Node.js. The abundance of resources and examples available can significantly speed up the learning process and troubleshooting.

  • typeorm:

    TypeORM has a growing community and solid documentation, especially for TypeScript developers. The availability of examples and community contributions helps developers navigate its features effectively.

How to Choose: bookshelf vs mongoose vs sequelize vs typeorm

  • bookshelf:

    Choose Bookshelf if you prefer a lightweight ORM that provides a simple interface for working with relational databases and supports both promises and callbacks. It is built on top of Knex.js and is ideal for projects that require flexibility and a straightforward approach to data modeling.

  • mongoose:

    Choose Mongoose if you are working specifically with MongoDB and need a schema-based solution to model your application data. Mongoose provides powerful features like validation, middleware, and population, making it an excellent choice for applications that require complex data relationships and validations.

  • sequelize:

    Choose Sequelize if you need a feature-rich ORM that supports multiple SQL dialects (Postgres, MySQL, SQLite, MSSQL) and offers a wide range of functionalities, including migrations, associations, and transaction management. It is suitable for applications that require a robust and flexible solution for managing relational data.

  • typeorm:

    Choose TypeORM if you are looking for a TypeScript-friendly ORM that supports both SQL and NoSQL databases. TypeORM is designed to work seamlessly with TypeScript, providing decorators and a rich set of features like lazy loading, migrations, and advanced query capabilities, making it ideal for TypeScript-based 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.