Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
M

mongoose

> 数据库
Open source

MongoDB object modeling designed to work in an asynchronous environment.

27.5K stars0 likes5 views
WebsiteGitHub

About

MongoDB object modeling designed to work in an asynchronous environment.

Mongoose

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

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

  • Stack Overflow
  • Bug Reports
  • Mongoose Slack Channel
  • Help Forum
  • MongoDB 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

bash
npm install mongoose

Using pnpm

bash
pnpm add mongoose

Using Yarn

bash
yarn add mongoose

Using Bun

bash
bun add mongoose

Mongoose 6.8.0 also includes alpha support for Deno.

Importing

javascript
// 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.

javascript
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.

bash
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.

javascript
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.

javascript
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:

  • Validators (async and sync)
  • Defaults
  • Getters
  • Setters
  • Indexes
  • Middleware
  • Methods definition
  • Statics definition
  • Plugins
  • pseudo-JOINs

The following example shows some of these features:

javascript
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

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

Or just do it all at once

javascript
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

javascript
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:

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

Or we can find documents from the same collection

javascript
await MyModel.find({});

You can also findOne, findById, update, etc.

javascript
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:

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

vs

javascript
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:

txt
comments: [Comment]

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

javascript
// 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:

javascript
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:

javascript
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 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:

javascript
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

  • run-rs
  • mongodb-memory-server
  • mongodb-topology-manager

Unofficial CLIs

  • mongoosejs-cli

Data Seeding

  • dookie
  • seedgoose
  • mongoose-data-seed

Express Session Stores

  • connect-mongodb-session
  • connect-mongo

License

Copyright (c) 2010 LearnBoost <[email protected]&

Issues· 176 open

View all issuesOpen on GitHub
  • #16539

    Map of arrays: set() followed by push(), pull() or addToSet() saves against the old array

    Updated Sep 29, 2026
  • #16530

    doc.set() on a nested path loses a nested value read from the same document (a.b becomes undefined)

    Updated Sep 25, 2026
  • #16524

    Model compiled while readyState reports a stale heartbeat never initializes: Model.init() stays pending and autoIndex never runs (9.10.2)

    Updated Sep 24, 2026
  • #16519

    Types: Type narrowing is lost for projection when chained with lean()

    Updated Sep 22, 2026
  • #16516

    Remove sift in favor of Mongoose-maintained lib

    backwards-breakingUpdated Sep 22, 2026
  • #13985

    Allow populating paths with spaces

    discussionbackwards-breakingUpdated Sep 15, 2026
  • #16506

    Run tests against TypeScript 7

    Updated Sep 11, 2026
  • #10367

    [Feature] support named parameters

    enhancementUpdated Sep 8, 2026
  • #8714

    Feature to undo/revert changes on a document (which haven't been persisted yet)

    new featureenhancementpluginUpdated Aug 19, 2026
  • #16284

    CI: fix/improve flaky tests

    Updated Jul 31, 2026

> Tags

JavaScriptmongomongodbnodejsodm

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 30, 2026
Category数据库
PricingOpen source

> Related tools

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库