mongoose vs sequelize vs bookshelf vs waterline
Node.js ORM Libraries
mongoosesequelizebookshelfwaterline類似套件:

Node.js ORM Libraries

Node.js ORM (Object-Relational Mapping) 庫是用於簡化與資料庫交互的工具,這些庫提供了一個抽象層,使開發者能夠使用 JavaScript 物件來進行資料庫操作,而不必直接編寫 SQL 查詢。這些庫各有特點,適用於不同的需求和開發風格,幫助開發者提高生產力,減少錯誤,並使代碼更具可讀性和可維護性。

npm下載趨勢

3 年

GitHub Stars 排名

統計詳情

套件
下載數
Stars
大小
Issues
發布時間
許可
mongoose8,721,07127,4542.19 MB20011 天前MIT
sequelize4,103,66730,3422.91 MB1,1128 個月前MIT
bookshelf06,344-2376 年前MIT
waterline05,3831.3 MB33-MIT

功能比較: mongoose vs sequelize vs bookshelf vs waterline

資料庫支持

  • mongoose:

    Mongoose 專為 MongoDB 設計,提供了強大的模式定義和數據驗證功能,適合需要複雜數據結構的應用。

  • sequelize:

    Sequelize 支持多種 SQL 資料庫,包括 MySQL、PostgreSQL、SQLite 和 MSSQL,並且提供了豐富的查詢功能和模型關聯支持。

  • bookshelf:

    Bookshelf 支持多種 SQL 資料庫,並且依賴於 Knex.js 作為查詢生成器,這使得它能夠靈活地與不同的資料庫進行交互。

  • waterline:

    Waterline 是一個資料存取層,支持多種資料庫,並提供統一的 API 來進行資料庫操作,適合需要靈活性的應用。

關聯模型

  • mongoose:

    Mongoose 也支持關聯模型,但主要是通過引用和嵌套文檔來實現,這使得處理複雜的數據結構變得簡單。

  • sequelize:

    Sequelize 提供了全面的關聯模型支持,開發者可以輕鬆地定義和查詢關聯,並且支持懶加載和預加載功能。

  • bookshelf:

    Bookshelf 提供了強大的關聯模型支持,允許開發者輕鬆地定義一對一、一對多和多對多的關聯,並且可以輕鬆地進行查詢。

  • waterline:

    Waterline 提供了靈活的關聯模型支持,允許開發者使用統一的 API 來定義和查詢關聯,適合多種資料庫。

學習曲線

  • mongoose:

    Mongoose 的學習曲線稍微陡峭,因為需要理解 MongoDB 的文檔模型和 Mongoose 的模式定義,但對於需要使用 MongoDB 的開發者來說,這是必須的。

  • sequelize:

    Sequelize 的學習曲線相對較高,因為它提供了豐富的功能和選項,開發者需要花時間去理解其 API 和查詢語法。

  • bookshelf:

    Bookshelf 的學習曲線相對較平緩,因為它的 API 設計簡單,並且依賴於 Knex.js,對於熟悉 SQL 的開發者來說,容易上手。

  • waterline:

    Waterline 的學習曲線較平緩,因為它提供了一個統一的 API,開發者可以輕鬆地在不同的資料庫之間切換。

擴展性

  • mongoose:

    Mongoose 提供了強大的擴展性,開發者可以通過中間件和插件來擴展其功能,並且可以輕鬆地處理複雜的數據驗證和轉換。

  • sequelize:

    Sequelize 的擴展性非常好,開發者可以輕鬆地創建自定義模型和方法,並且支持多種查詢選項和操作。

  • bookshelf:

    Bookshelf 具有良好的擴展性,開發者可以輕鬆地創建自定義模型和方法,並且可以與 Knex.js 結合使用,進行更複雜的查詢。

  • waterline:

    Waterline 的擴展性較好,開發者可以根據需要創建自定義適配器,並且可以輕鬆地在不同的資料庫之間切換。

維護性

  • mongoose:

    Mongoose 的維護性也較高,因為它提供了清晰的模式定義和數據驗證,這使得代碼更具可讀性和可維護性。

  • sequelize:

    Sequelize 的維護性較高,因為其 API 設計清晰,並且提供了豐富的文檔和社區支持,方便開發者進行維護。

  • bookshelf:

    Bookshelf 的維護性較高,因為其代碼結構簡單,並且依賴於 Knex.js,這使得代碼的可讀性和可維護性都得到了提升。

  • waterline:

    Waterline 的維護性較高,因為它提供了一個統一的 API,開發者可以輕鬆地在不同的資料庫之間切換,並且代碼結構簡單易懂。

如何選擇: mongoose vs sequelize vs bookshelf vs waterline

  • mongoose:

    選擇 Mongoose 如果你正在使用 MongoDB,因為它提供了強大的模式定義和數據驗證功能,並且能夠輕鬆地處理複雜的數據結構和關聯。

  • sequelize:

    選擇 Sequelize 如果你需要一個功能全面的 ORM,支持多種 SQL 資料庫(如 MySQL、PostgreSQL、SQLite 和 MSSQL),並且需要強大的查詢功能和模型關聯支持。

  • bookshelf:

    選擇 Bookshelf 如果你需要一個輕量級的 ORM,並且希望利用 Knex.js 作為查詢生成器,Bookshelf 提供了靈活的關聯模型和支持多種資料庫的能力。

  • waterline:

    選擇 Waterline 如果你需要一個支持多種資料庫的 ORM,並且希望使用一個統一的 API 來進行資料庫操作,Waterline 提供了靈活的資料存取層,適合用於 Sails.js 框架。

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 request 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 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/[email protected]/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 Studio

Mongoose Studio is a free, fully open-source, browser-based MongoDB GUI built by the Mongoose team for apps that already use Mongoose. Install @mongoosejs/studio from npm and run it alongside your app as Express middleware, or deploy it on Vercel or Netlify, to browse and edit documents, query with your existing models and schemas with autocomplete, build dashboards, visualize and edit GeoJSON, and use AI-assisted MongoDB workflows without moving data into a hosted third-party workspace or sharing raw MongoDB connection strings.

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();
});

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 is 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 <[email protected]>

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.