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

Node.js ORM libraries provide a way to interact with databases using object-oriented programming principles. They abstract the database interactions, allowing developers to work with JavaScript objects instead of writing raw SQL queries. This enhances productivity and maintainability by providing a more intuitive interface for database operations. Each library has its unique features, design philosophies, and supported database systems, making them suitable for different use cases in web development.

NPM Package Downloads Trend
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
mongoose2,649,52826,9612.75 MB2425 days agoMIT
typeorm2,098,06234,23620.4 MB2,59710 months agoMIT
sequelize1,849,21529,5732.91 MB95219 days agoMIT
knex1,811,25919,342874 kB1,163a year agoMIT
bookshelf57,8656,361-2364 years agoMIT
Feature Comparison: mongoose vs typeorm vs sequelize vs knex vs bookshelf

Database Support

  • mongoose: Mongoose is specifically designed for MongoDB, providing a powerful schema-based solution for modeling application data. It leverages MongoDB's features and is tailored for NoSQL data management.
  • typeorm: TypeORM supports both SQL databases (like PostgreSQL, MySQL, and SQLite) and NoSQL databases (like MongoDB). This flexibility makes it suitable for applications that require a mix of data storage solutions.
  • sequelize: Sequelize supports a wide range of SQL databases, including PostgreSQL, MySQL, MariaDB, SQLite, and Microsoft SQL Server. It provides a unified API for interacting with these databases, making it easy to switch between them.
  • knex: Knex is a SQL query builder that supports multiple database systems, including PostgreSQL, MySQL, SQLite, and Oracle. It allows developers to write database-agnostic queries, making it versatile for different projects.
  • bookshelf: Bookshelf supports various SQL databases through Knex.js, including PostgreSQL, MySQL, and SQLite. It is designed to work seamlessly with these relational databases, providing a simple interface for CRUD operations.

Learning Curve

  • mongoose: Mongoose has a steeper learning curve due to its schema-based approach and the need to understand MongoDB's data model. However, its extensive documentation and community support can help ease the learning process.
  • typeorm: TypeORM's learning curve can be steep for those unfamiliar with TypeScript or decorators. However, TypeScript developers may find its type safety and modern features beneficial once they overcome the initial learning phase.
  • sequelize: Sequelize has a moderate learning curve, with many features and options available. Understanding its associations, migrations, and advanced querying capabilities may take some time for new users.
  • knex: Knex has a relatively low learning curve for developers familiar with SQL. Its query-building syntax is intuitive, but those new to SQL may need to invest time in learning SQL concepts.
  • bookshelf: Bookshelf has a moderate learning curve, especially for those already familiar with Knex.js. Its simplicity and lightweight nature make it easy to pick up, but advanced features may require deeper understanding.

Extensibility

  • mongoose: Mongoose is extensible through middleware and custom validators, enabling developers to add functionality to their schemas. Its schema-based approach allows for easy customization of data models.
  • typeorm: TypeORM is extensible with decorators and custom repositories, allowing developers to create reusable components. Its architecture supports a wide range of extensions and customizations.
  • sequelize: Sequelize is highly extensible, offering hooks, custom validators, and the ability to define complex associations. Developers can easily extend its functionality to meet specific application needs.
  • knex: Knex is highly extensible, allowing developers to create custom query builders and integrate with various plugins. Its flexibility makes it suitable for a wide range of database interactions.
  • bookshelf: Bookshelf is extensible through plugins and custom models, allowing developers to add functionality as needed. However, it is less feature-rich compared to more comprehensive ORMs.

Performance

  • mongoose: Mongoose provides good performance for MongoDB applications, but its schema validation and middleware can introduce some overhead. Proper indexing and optimization are essential for maintaining performance.
  • typeorm: TypeORM offers good performance, especially with TypeScript's type safety. However, like Sequelize, complex relationships and queries may affect performance, so optimization is crucial.
  • sequelize: Sequelize's performance is generally solid, but complex queries and associations can lead to slower response times. Developers need to be mindful of optimizing queries and using eager loading appropriately.
  • knex: Knex is designed for performance, allowing developers to write efficient SQL queries. Its lightweight nature means it has minimal overhead, making it suitable for high-performance applications.
  • bookshelf: Bookshelf's performance is generally good for most applications, but it may lag behind more optimized ORMs in complex scenarios due to its reliance on Knex.js for query building.

Community and Documentation

  • mongoose: Mongoose has a large and active community, with extensive documentation and numerous tutorials available. This makes it easy for developers to find help and resources when needed.
  • typeorm: TypeORM has a growing community and good documentation, especially for TypeScript developers. While it may not be as extensive as others, it is actively maintained and supported.
  • sequelize: Sequelize boasts a large community and excellent documentation, providing a wealth of resources, examples, and support for developers. Its popularity ensures that many common issues have been addressed in the community.
  • knex: Knex has a strong community and comprehensive documentation, making it easy for developers to find resources and support. Its popularity ensures a wealth of tutorials and examples are available.
  • bookshelf: Bookshelf has a smaller community compared to larger ORMs but offers decent documentation. Community support may be limited, but the library is straightforward to use.
How to Choose: mongoose vs typeorm vs sequelize vs knex vs bookshelf
  • mongoose: Choose Mongoose if you are working with MongoDB and need a robust schema-based solution for modeling your data. Mongoose provides built-in validation, middleware, and a rich set of features tailored for MongoDB, making it ideal for applications that leverage NoSQL databases.
  • typeorm: Choose TypeORM if you prefer a TypeScript-first ORM that supports both SQL and NoSQL databases. TypeORM offers decorators and an active record pattern, making it a good choice for TypeScript developers who want to leverage type safety and modern JavaScript features.
  • sequelize: Choose Sequelize if you want a feature-rich ORM that supports multiple SQL dialects (PostgreSQL, MySQL, SQLite, etc.) and offers a comprehensive set of features including migrations, associations, and transactions. It is suitable for applications that require complex relationships and advanced querying capabilities.
  • knex: Choose Knex if you need a flexible SQL query builder that can work with multiple database systems. It is not an ORM but provides a powerful way to construct SQL queries programmatically, making it suitable for applications that require custom SQL logic without the overhead of an ORM.
  • bookshelf: Choose Bookshelf if you prefer a simple and lightweight ORM that is built on top of Knex.js. It is great for projects that require a straightforward, promise-based interface for working with relational databases and supports a variety of database engines.
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.