These libraries are Object-Relational Mappers (ORMs) for Node.js. They let you interact with databases using JavaScript objects instead of writing raw SQL queries. This is useful for frontend developers working in full-stack roles where the backend is also JavaScript. Each tool handles database connections, model definitions, and data fetching differently.
These libraries help Node.js applications interact with databases using JavaScript instead of raw SQL. For frontend developers moving into full-stack roles, understanding these tools is key to building robust backends. While they all solve the same problem, their approaches and maintenance status differ greatly.
How you define your database tables varies significantly between these tools.
sequelize uses a definition function or class syntax with explicit data types.
// sequelize
const User = sequelize.define('User', {
firstName: DataTypes.STRING,
lastName: DataTypes.STRING
});
objection uses ES6 classes and a static getter for the table name.
// objection
class User extends Model {
static get tableName() {
return 'users';
}
}
bookshelf extends a base model object with a configuration hash.
// bookshelf
const User = bookshelf.Model.extend({
tableName: 'users'
});
waterline uses a plain object export with an attributes key.
// waterline
module.exports = {
attributes: {
firstName: 'string',
lastName: 'string'
}
};
Querying data shows the difference in flexibility and syntax style.
sequelize provides a high-level API with objects for conditions.
// sequelize
const users = await User.findAll({
where: { lastName: 'Smith' }
});
objection uses a query builder chain that feels very natural.
// objection
const users = await User.query()
.where('lastName', 'Smith');
bookshelf relies on chaining methods on the model constructor.
// bookshelf
const users = await User.where('lastName', 'Smith')
.fetchAll();
waterline uses a simple find method with a criteria object.
// waterline
const users = await User.find({
where: { lastName: 'Smith' }
});
Linking tables together is where ORMs save the most time.
sequelize defines associations explicitly between models.
// sequelize
User.hasMany(Post);
const user = await User.findOne({
include: [Post]
});
objection defines relations in a static getter on the model class.
// objection
class User extends Model {
static get relationMappings() {
return {
posts: {
relation: Model.HasManyRelation,
modelClass: Post
}
};
}
}
bookshelf defines relations as methods on the model prototype.
// bookshelf
const User = bookshelf.Model.extend({
posts: function() {
return this.hasMany(Post);
}
});
waterline defines associations inside the attributes object.
// waterline
module.exports = {
attributes: {
posts: {
collection: 'post',
via: 'author'
}
}
};
This is a critical factor for long-term project health.
sequelize is actively maintained with frequent releases. It has a large community and strong TypeScript definitions. This makes it a safe bet for new projects.
objection is also well-maintained and benefits from the knex query builder ecosystem. It is a great choice if you need more control than sequelize offers.
bookshelf has seen reduced activity in recent years. While stable, it lacks the momentum of newer tools. You might find fewer plugins or community answers.
waterline is tightly coupled with Sails.js. The Sails ecosystem has shrunk compared to Express or NestJS. Using this outside of Sails is uncommon and may lead to integration issues.
| Feature | sequelize | objection | bookshelf | waterline |
|---|---|---|---|---|
| Base | Custom Query Generator | Built on knex | Built on knex | Custom Adapter Layer |
| Style | Class or Define Function | ES6 Classes | Prototype Extend | Object Export |
| Querying | High-Level API | Query Builder Chain | Chain Methods | Criteria Object |
| Status | โ Active | โ Active | โ ๏ธ Low Activity | โ ๏ธ Sails Specific |
For most new full-stack JavaScript projects, sequelize or objection are the top choices. sequelize is better if you want everything built-in and ready to go. objection is better if you want flexibility and don't mind writing a bit more query logic.
Avoid bookshelf and waterline for new greenfield projects unless you have a specific reason. bookshelf is largely legacy at this point โ there are more modern tools available. waterline is best left for existing Sails.js applications rather than new standalone backends.
Final Thought: Your ORM choice impacts how easily you can change database logic later. Pick the tool with the active community โ it makes debugging much easier when you get stuck.
Choose bookshelf only if you are maintaining an older legacy system that already uses it. Development activity has slowed significantly compared to modern alternatives. For new projects, there are better options with more active communities and newer features.
Choose objection if you need flexible query building for complex SQL operations. It is built on top of knex, so you can drop down to raw query building when needed. This fits projects where data relationships are complex and performance tuning is critical.
Choose sequelize if you want a stable, feature-complete ORM with strong TypeScript support. It is the standard choice for SQL databases in Node.js and offers built-in migrations and validation. This is best for teams that prefer convention over configuration and need long-term stability.
Choose waterline only if you are working within the Sails.js framework ecosystem. It is designed to work with multiple database types using adapters, but this abstraction can limit performance. For standalone Node.js backends, other ORMs provide more direct control and better maintenance.
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.
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.
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', {
// ...
})
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)
})
.set() on a model.Model, adding timestamps, attribute validation and some native CRUD methods.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.
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.
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.
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.
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.
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)
})
See the CONTRIBUTING document on GitHub.
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.
We found the following projects using Bookshelf, but there can be more: