Which is Better Node.js ORM Libraries?
mongoose vs sequelize vs bookshelf vs waterline
1 Year
mongoosesequelizebookshelfwaterlineSimilar Packages:
What's Node.js ORM Libraries?

Node.js ORM (Object-Relational Mapping) libraries facilitate the interaction between applications and databases by abstracting the complexities of SQL queries and providing a more intuitive way to manage data. These libraries allow developers to work with database records as if they were JavaScript objects, streamlining CRUD operations and enhancing productivity. Each library has its own strengths, design philosophies, and use cases, making it essential to choose the right one based on project requirements and developer preferences.

NPM Package Downloads Trend
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
mongoose2,410,73126,9502.75 MB2388 days agoMIT
sequelize1,774,83729,5592.91 MB95114 days agoMIT
bookshelf61,0486,361-2364 years agoMIT
waterline17,9455,4111.3 MB32-MIT
Feature Comparison: mongoose vs sequelize vs bookshelf vs waterline

Database Support

  • mongoose: Mongoose is specifically designed for MongoDB, providing a rich set of features tailored to document-based databases. It allows for schema definitions, data validation, and middleware, making it ideal for applications that leverage MongoDB's capabilities.
  • sequelize: Sequelize supports multiple SQL dialects, including PostgreSQL, MySQL, SQLite, and MSSQL. This flexibility allows developers to switch databases with minimal changes to their codebase, making it a versatile choice for various projects.
  • bookshelf: Bookshelf supports SQL databases through Knex.js, allowing for a wide range of SQL dialects. It is designed for relational databases and excels in managing relationships between models, making it suitable for applications that require complex data structures.
  • waterline: Waterline provides a unified API for interacting with different databases, including both SQL and NoSQL options. This abstraction allows developers to switch between different data sources without significant changes to their code, promoting flexibility in data management.

Learning Curve

  • mongoose: Mongoose has a steeper learning curve due to its schema-based approach and extensive feature set. Developers need to familiarize themselves with its concepts of models, schemas, and middleware, which can be overwhelming for beginners.
  • sequelize: Sequelize offers a comprehensive API, which can lead to a steeper learning curve for new users. However, its extensive documentation and community support help mitigate this challenge, making it accessible for developers willing to invest time in learning.
  • bookshelf: Bookshelf has a moderate learning curve, especially for those familiar with Knex.js. Its simplicity and flexibility make it relatively easy to grasp, but understanding its relationship management features may require some time.
  • waterline: Waterline has a gentle learning curve, particularly for those already using Sails.js. Its straightforward API allows developers to quickly understand its usage, although mastering its full capabilities may take additional time.

Extensibility

  • mongoose: Mongoose is highly extensible, supporting custom validators, middleware, and plugins. This allows developers to enhance their models with additional functionality, making it a powerful choice for complex applications.
  • sequelize: Sequelize offers a wide range of hooks and lifecycle events that allow for extensive customization and extensibility. Developers can easily add custom logic to their models, enhancing their functionality without altering the core library.
  • bookshelf: Bookshelf is designed to be extensible, allowing developers to create custom model methods and extend its functionality as needed. This flexibility makes it suitable for projects that require tailored solutions.
  • waterline: Waterline provides a modular architecture that allows for the creation of custom adapters and queries. This extensibility makes it suitable for applications with unique data access requirements.

Performance

  • mongoose: Mongoose is optimized for MongoDB and performs well with large datasets. Its schema-based approach can lead to performance improvements through data validation and indexing, although improper schema design can hinder performance.
  • sequelize: Sequelize is designed for performance and scalability, offering features like lazy loading and eager loading to optimize database interactions. Its support for multiple SQL dialects allows for performance tuning based on the underlying database.
  • bookshelf: Bookshelf's performance is generally good, but it may not be as optimized as other ORMs for complex queries. Its reliance on Knex.js for query building can lead to efficient SQL generation, but performance may vary based on usage patterns.
  • waterline: Waterline's performance can vary depending on the underlying database and the complexity of queries. While it provides a consistent API, developers may need to optimize their queries and data access patterns to achieve the best performance.

Community and Support

  • mongoose: Mongoose has a large and active community, with extensive documentation, tutorials, and plugins available. This strong support network makes it easier for developers to find solutions and best practices.
  • sequelize: Sequelize boasts a robust community and extensive documentation, making it one of the most popular ORMs for Node.js. Its active development and large user base contribute to a wealth of resources and third-party plugins.
  • bookshelf: Bookshelf has a smaller community compared to other ORMs, which may result in fewer resources and plugins. However, its integration with Knex.js provides access to a broader community for query building.
  • waterline: Waterline has a smaller community, primarily focused on Sails.js users. While it may not have as many resources as other ORMs, its integration with Sails.js provides a supportive environment for those using the framework.
How to Choose: mongoose vs sequelize vs bookshelf vs waterline
  • mongoose: Choose Mongoose if you are working with MongoDB and need a robust schema-based solution that supports data validation, middleware, and complex queries. Mongoose is particularly suitable for applications that require a strong structure and validation for their data models, making it a popular choice for Node.js applications using MongoDB.
  • sequelize: Choose Sequelize if you need a feature-rich ORM that supports multiple SQL dialects (PostgreSQL, MySQL, SQLite, MSSQL) and offers a comprehensive set of features including migrations, associations, and hooks. It is well-suited for larger applications that require advanced querying capabilities and a strong focus on performance and scalability.
  • bookshelf: Choose Bookshelf if you prefer a lightweight ORM that provides a simple and flexible way to interact with SQL databases, especially if you are already using Knex.js for query building. It is ideal for projects that require a straightforward approach to data modeling and relationships without the overhead of a full-fledged ORM.
  • waterline: Choose Waterline if you are looking for a data access layer that provides a simple and consistent API for interacting with various databases, including SQL and NoSQL options. It is particularly useful for applications built with the Sails.js framework, as it integrates seamlessly with its architecture and supports a wide range of database backends.
README for mongoose

Mongoose

Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. Mongoose supports Node.js and Deno (alpha).

Build Status NPM version Deno version Deno popularity

npm

Documentation

The official documentation website is mongoosejs.com.

Mongoose 8.0.0 was released on October 31, 2023. You can find more details on backwards breaking changes in 8.0.0 on our docs site.

Support

Plugins

Check out the plugins search site to see hundreds of related modules from the community. Next, learn how to write your own plugin from the docs or this blog post.

Contributors

Pull requests are always welcome! Please base pull requests against the master branch and follow the contributing guide.

If your pull requests makes documentation changes, please do not modify any .html files. The .html files are compiled code, so please make your changes in docs/*.pug, lib/*.js, or test/docs/*.js.

View all 400+ contributors.

Installation

First install Node.js and MongoDB. Then:

npm install mongoose

Mongoose 6.8.0 also includes alpha support for Deno.

Importing

// Using Node.js `require()`
const mongoose = require('mongoose');

// Using ES6 imports
import mongoose from 'mongoose';

Or, using Deno's createRequire() for CommonJS support as follows.

import { createRequire } from 'https://deno.land/std@0.177.0/node/module.ts';
const require = createRequire(import.meta.url);

const mongoose = require('mongoose');

mongoose.connect('mongodb://127.0.0.1:27017/test')
  .then(() => console.log('Connected!'));

You can then run the above script using the following.

deno run --allow-net --allow-read --allow-sys --allow-env mongoose-test.js

Mongoose for Enterprise

Available as part of the Tidelift Subscription

The maintainers of mongoose and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.

Overview

Connecting to MongoDB

First, we need to define a connection. If your app uses only one database, you should use mongoose.connect. If you need to create additional connections, use mongoose.createConnection.

Both connect and createConnection take a mongodb:// URI, or the parameters host, database, port, options.

await mongoose.connect('mongodb://127.0.0.1/my_database');

Once connected, the open event is fired on the Connection instance. If you're using mongoose.connect, the Connection is mongoose.connection. Otherwise, mongoose.createConnection return value is a Connection.

Note: If the local connection fails then try using 127.0.0.1 instead of localhost. Sometimes issues may arise when the local hostname has been changed.

Important! Mongoose buffers all the commands until it's connected to the database. This means that you don't have to wait until it connects to MongoDB in order to define models, run queries, etc.

Defining a Model

Models are defined through the Schema interface.

const Schema = mongoose.Schema;
const ObjectId = Schema.ObjectId;

const BlogPost = new Schema({
  author: ObjectId,
  title: String,
  body: String,
  date: Date
});

Aside from defining the structure of your documents and the types of data you're storing, a Schema handles the definition of:

The following example shows some of these features:

const Comment = new Schema({
  name: { type: String, default: 'hahaha' },
  age: { type: Number, min: 18, index: true },
  bio: { type: String, match: /[a-z]/ },
  date: { type: Date, default: Date.now },
  buff: Buffer
});

// a setter
Comment.path('name').set(function(v) {
  return capitalize(v);
});

// middleware
Comment.pre('save', function(next) {
  notify(this.get('email'));
  next();
});

Take a look at the example in examples/schema/schema.js for an end-to-end example of a typical setup.

Accessing a Model

Once we define a model through mongoose.model('ModelName', mySchema), we can access it through the same function

const MyModel = mongoose.model('ModelName');

Or just do it all at once

const MyModel = mongoose.model('ModelName', mySchema);

The first argument is the singular name of the collection your model is for. Mongoose automatically looks for the plural version of your model name. For example, if you use

const MyModel = mongoose.model('Ticket', mySchema);

Then MyModel will use the tickets collection, not the ticket collection. For more details read the model docs.

Once we have our model, we can then instantiate it, and save it:

const instance = new MyModel();
instance.my.key = 'hello';
await instance.save();

Or we can find documents from the same collection

await MyModel.find({});

You can also findOne, findById, update, etc.

const instance = await MyModel.findOne({ /* ... */ });
console.log(instance.my.key); // 'hello'

For more details check out the docs.

Important! If you opened a separate connection using mongoose.createConnection() but attempt to access the model through mongoose.model('ModelName') it will not work as expected since it is not hooked up to an active db connection. In this case access your model through the connection you created:

const conn = mongoose.createConnection('your connection string');
const MyModel = conn.model('ModelName', schema);
const m = new MyModel();
await m.save(); // works

vs

const conn = mongoose.createConnection('your connection string');
const MyModel = mongoose.model('ModelName', schema);
const m = new MyModel();
await m.save(); // does not work b/c the default connection object was never connected

Embedded Documents

In the first example snippet, we defined a key in the Schema that looks like:

comments: [Comment]

Where Comment is a Schema we created. This means that creating embedded documents is as simple as:

// retrieve my model
const BlogPost = mongoose.model('BlogPost');

// create a blog post
const post = new BlogPost();

// create a comment
post.comments.push({ title: 'My comment' });

await post.save();

The same goes for removing them:

const post = await BlogPost.findById(myId);
post.comments[0].deleteOne();
await post.save();

Embedded documents enjoy all the same features as your models. Defaults, validators, middleware.

Middleware

See the docs page.

Intercepting and mutating method arguments

You can intercept method arguments via middleware.

For example, this would allow you to broadcast changes about your Documents every time someone sets a path in your Document to a new value:

schema.pre('set', function(next, path, val, typel) {
  // `this` is the current Document
  this.emit('set', path, val);

  // Pass control to the next pre
  next();
});

Moreover, you can mutate the incoming method arguments so that subsequent middleware see different values for those arguments. To do so, just pass the new values to next:

schema.pre(method, function firstPre(next, methodArg1, methodArg2) {
  // Mutate methodArg1
  next('altered-' + methodArg1.toString(), methodArg2);
});

// pre declaration is chainable
schema.pre(method, function secondPre(next, methodArg1, methodArg2) {
  console.log(methodArg1);
  // => 'altered-originalValOfMethodArg1'

  console.log(methodArg2);
  // => 'originalValOfMethodArg2'

  // Passing no arguments to `next` automatically passes along the current argument values
  // i.e., the following `next()` is equivalent to `next(methodArg1, methodArg2)`
  // and also equivalent to, with the example method arg
  // values, `next('altered-originalValOfMethodArg1', 'originalValOfMethodArg2')`
  next();
});

Schema gotcha

type, when used in a schema has special meaning within Mongoose. If your schema requires using type as a nested property you must use object notation:

new Schema({
  broken: { type: Boolean },
  asset: {
    name: String,
    type: String // uh oh, it broke. asset will be interpreted as String
  }
});

new Schema({
  works: { type: Boolean },
  asset: {
    name: String,
    type: { type: String } // works. asset is an object with a type property
  }
});

Driver Access

Mongoose is built on top of the official MongoDB Node.js driver. Each mongoose model keeps a reference to a native MongoDB driver collection. The collection object can be accessed using YourModel.collection. However, using the collection object directly bypasses all mongoose features, including hooks, validation, etc. The one notable exception that YourModel.collection still buffers commands. As such, YourModel.collection.find() will not return a cursor.

API Docs

Find the API docs here, generated using dox and acquit.

Related Projects

MongoDB Runners

Unofficial CLIs

Data Seeding

Express Session Stores

License

Copyright (c) 2010 LearnBoost <dev@learnboost.com>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.