mongoose vs sequelize vs bookshelf vs waterline
Node.js ORM Libraries
mongoosesequelizebookshelfwaterline类似的npm包:
Node.js ORM Libraries

Node.js ORM(对象关系映射)库是用于简化与数据库交互的工具,它们允许开发者通过对象而不是直接使用SQL查询来操作数据库。这些库提供了一种更高层次的抽象,使得数据库操作更加直观和易于维护。ORM库通常支持多种数据库,并提供模型定义、查询构建和数据验证等功能,从而提高开发效率和代码可读性。

npm下载趋势
3 年
GitHub Stars 排名
统计详情
npm包名称
下载量
Stars
大小
Issues
发布时间
License
mongoose4,089,92027,4282.03 MB2128 天前MIT
sequelize2,474,54530,2752.91 MB9999 个月前MIT
bookshelf84,8676,365-2376 年前MIT
waterline26,7005,4081.3 MB34-MIT
功能对比: mongoose vs sequelize vs bookshelf vs waterline

数据库支持

  • mongoose:

    Mongoose专为MongoDB设计,提供了强大的Schema定义和数据验证功能。它支持MongoDB的所有特性,如嵌套文档和数组,适合需要复杂数据结构的应用。

  • sequelize:

    Sequelize支持多种SQL数据库,包括PostgreSQL、MySQL、MariaDB、SQLite和Microsoft SQL Server。它提供了强大的模型关联和事务管理功能,适合需要复杂查询和数据关系的应用。

  • bookshelf:

    Bookshelf是一个轻量级的ORM,基于Knex.js,支持多种SQL数据库,如PostgreSQL、MySQL和SQLite。它允许开发者灵活地定义模型和关系,适合需要简单数据库交互的项目。

  • waterline:

    Waterline是Sails.js的ORM,支持多种数据源,包括SQL和NoSQL数据库。它提供了一致的API来处理不同类型的数据库,适合需要快速开发和多种数据库支持的项目。

学习曲线

  • mongoose:

    Mongoose的学习曲线稍陡,因为它提供了丰富的功能和复杂的Schema定义。对于需要深入理解MongoDB特性的开发者来说,Mongoose是一个不错的选择。

  • sequelize:

    Sequelize的学习曲线适中,虽然功能强大,但其文档详细且易于理解。开发者可以快速掌握基本用法,并逐步深入复杂功能。

  • bookshelf:

    Bookshelf的学习曲线相对较平缓,特别是对于已经熟悉Knex.js的开发者。它的API简单易懂,适合快速上手和小型项目。

  • waterline:

    Waterline的学习曲线较为平缓,特别是对于Sails.js用户。它的API设计简单,适合快速开发和原型制作,但对于复杂查询可能需要额外学习。

功能丰富性

  • mongoose:

    Mongoose功能丰富,支持数据验证、钩子、虚拟属性等,适合需要复杂数据操作和验证的应用。

  • sequelize:

    Sequelize功能全面,支持事务、关联、复杂查询和数据验证,适合需要强大数据操作能力的应用。

  • bookshelf:

    Bookshelf提供了基本的CRUD操作和关系支持,但在功能上相对简单,适合需要轻量级解决方案的项目。

  • waterline:

    Waterline提供了简单的API来处理多种数据源,但在功能上可能不如其他ORM强大,适合快速开发和原型制作。

扩展性

  • mongoose:

    Mongoose具有良好的扩展性,支持中间件和插件机制,开发者可以轻松添加自定义功能和逻辑。

  • sequelize:

    Sequelize的扩展性强,支持自定义模型方法和钩子,适合需要复杂业务逻辑的应用。

  • bookshelf:

    Bookshelf的扩展性较好,支持自定义模型和关系,开发者可以根据项目需求灵活扩展功能。

  • waterline:

    Waterline的扩展性相对较弱,虽然支持多种数据源,但在复杂功能扩展方面可能不如其他ORM灵活。

社区支持

  • mongoose:

    Mongoose拥有活跃的社区和丰富的文档,开发者可以轻松找到解决方案和示例。

  • sequelize:

    Sequelize拥有庞大的社区和良好的文档支持,开发者可以获得大量的资源和帮助。

  • bookshelf:

    Bookshelf的社区支持相对较小,但由于其基于Knex.js,开发者可以从Knex.js的文档和社区获得帮助。

  • waterline:

    Waterline的社区支持主要集中在Sails.js框架中,文档相对较少,但对于Sails.js用户来说,支持还是可以的。

如何选择: mongoose vs sequelize vs bookshelf vs waterline
  • mongoose:

    选择Mongoose如果你专注于MongoDB,并且需要一个功能丰富的库来处理数据模型、验证和中间件。Mongoose提供了强大的Schema定义和数据验证功能,非常适合需要复杂数据结构的应用。

  • sequelize:

    选择Sequelize如果你需要一个功能全面的ORM,支持多种SQL数据库(如PostgreSQL、MySQL、SQLite等),并且希望利用其强大的事务管理和模型关联功能。Sequelize适合需要复杂查询和数据关系的应用。

  • bookshelf:

    选择Bookshelf如果你需要一个轻量级的ORM,支持Knex.js作为查询构建器,并且希望能够灵活地处理多种数据库关系。它适合那些喜欢使用Promise和链式调用的开发者。

  • waterline:

    选择Waterline如果你需要一个支持多种数据源的ORM,尤其是在Sails.js框架中使用时。Waterline提供了简单的API来处理不同类型的数据库,并且支持灵活的数据模型定义。它适合需要快速开发和多种数据库支持的项目。

mongoose的README

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 9.0.0 was released on November 21, 2025. You can find more details on backwards breaking changes in 9.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:

Then install the mongoose package using your preferred package manager:

Using npm

npm install mongoose

Using pnpm

pnpm add mongoose

Using Yarn

yarn add mongoose

Using Bun

bun add 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

Mongoose API documentation, 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.