{"id":14956768,"url":"https://github.com/automattic/mongoose","last_synced_at":"2026-03-10T22:12:09.102Z","repository":{"id":861933,"uuid":"597879","full_name":"Automattic/mongoose","owner":"Automattic","description":"MongoDB object modeling designed to work in an asynchronous environment.","archived":false,"fork":false,"pushed_at":"2025-05-02T18:55:55.000Z","size":138392,"stargazers_count":27215,"open_issues_count":229,"forks_count":3862,"subscribers_count":481,"default_branch":"master","last_synced_at":"2025-05-05T13:57:54.578Z","etag":null,"topics":["mongo","mongodb","nodejs","odm","orm"],"latest_commit_sha":null,"homepage":"https://mongoosejs.com","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Automattic.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":"mongoosejs","open_collective":"mongoose","tidelift":"npm/mongoose"}},"created_at":"2010-04-06T21:39:05.000Z","updated_at":"2025-05-05T02:16:35.000Z","dependencies_parsed_at":"2023-09-25T19:53:04.869Z","dependency_job_id":"2de8d810-c6a3-433d-8136-726b60af222a","html_url":"https://github.com/Automattic/mongoose","commit_stats":{"total_commits":17110,"total_committers":952,"mean_commits":"17.972689075630253","dds":0.6200467562828755,"last_synced_commit":"830b010c848cd35e7aafe32656dac7e8178dcb92"},"previous_names":["learnboost/mongoose"],"tags_count":924,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Automattic%2Fmongoose","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Automattic%2Fmongoose/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Automattic%2Fmongoose/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Automattic%2Fmongoose/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Automattic","download_url":"https://codeload.github.com/Automattic/mongoose/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253761436,"owners_count":21960147,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["mongo","mongodb","nodejs","odm","orm"],"created_at":"2024-09-24T13:13:28.042Z","updated_at":"2025-12-16T14:51:09.908Z","avatar_url":"https://github.com/Automattic.png","language":"JavaScript","funding_links":["https://github.com/sponsors/mongoosejs","https://opencollective.com/mongoose","https://tidelift.com/funding/github/npm/mongoose","https://tidelift.com/subscription/pkg/npm-mongoose?utm_source=npm-mongoose\u0026utm_medium=referral\u0026utm_campaign=enterprise\u0026utm_term=repo"],"categories":[],"sub_categories":[],"readme":"# Mongoose\n\nMongoose is a [MongoDB](https://www.mongodb.org/) object modeling tool designed to work in an asynchronous environment. Mongoose supports [Node.js](https://nodejs.org/en/) and [Deno](https://deno.land/) (alpha).\n\n[![Build Status](https://github.com/Automattic/mongoose/workflows/Test/badge.svg)](https://github.com/Automattic/mongoose)\n[![NPM version](https://badge.fury.io/js/mongoose.svg)](http://badge.fury.io/js/mongoose)\n[![Deno version](https://deno.land/badge/mongoose/version)](https://deno.land/x/mongoose)\n[![Deno popularity](https://deno.land/badge/mongoose/popularity)](https://deno.land/x/mongoose)\n\n[![npm](https://nodei.co/npm/mongoose.png)](https://www.npmjs.com/package/mongoose)\n\n## Documentation\n\nThe official documentation website is [mongoosejs.com](http://mongoosejs.com/).\n\nMongoose 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](https://mongoosejs.com/docs/migrating_to_9.html).\n\n## Support\n\n* [Stack Overflow](http://stackoverflow.com/questions/tagged/mongoose)\n* [Bug Reports](https://github.com/Automattic/mongoose/issues/)\n* [Mongoose Slack Channel](http://slack.mongoosejs.io/)\n* [Help Forum](http://groups.google.com/group/mongoose-orm)\n* [MongoDB Support](https://www.mongodb.com/docs/manual/support/)\n\n## Plugins\n\nCheck out the [plugins search site](http://plugins.mongoosejs.io/) to see hundreds of related modules from the community. Next, learn how to write your own plugin from the [docs](http://mongoosejs.com/docs/plugins.html) or [this blog post](http://thecodebarbarian.com/2015/03/06/guide-to-mongoose-plugins).\n\n## Contributors\n\nPull requests are always welcome! Please base pull requests against the `master`\nbranch and follow the [contributing guide](https://github.com/Automattic/mongoose/blob/master/CONTRIBUTING.md).\n\nIf your pull requests makes documentation changes, please do **not**\nmodify any `.html` files. The `.html` files are compiled code, so please make\nyour changes in `docs/*.pug`, `lib/*.js`, or `test/docs/*.js`.\n\nView all 400+ [contributors](https://github.com/Automattic/mongoose/graphs/contributors).\n\n## Installation\n\nFirst install [Node.js](http://nodejs.org/) and [MongoDB](https://www.mongodb.org/downloads). Then:\n\nThen install the `mongoose` package using your preferred package manager:\n\n### Using npm\n\n```sh\nnpm install mongoose\n```\n\n### Using pnpm\n\n```sh\npnpm add mongoose\n```\n\n### Using Yarn\n\n```sh\nyarn add mongoose\n```\n\n### Using Bun\n\n```sh\nbun add mongoose\n```\n\nMongoose 6.8.0 also includes alpha support for [Deno](https://deno.land/).\n\n## Importing\n\n```javascript\n// Using Node.js `require()`\nconst mongoose = require('mongoose');\n\n// Using ES6 imports\nimport mongoose from 'mongoose';\n```\n\nOr, using [Deno's `createRequire()` for CommonJS support](https://deno.land/std@0.113.0/node/README.md?source=#commonjs-modules-loading) as follows.\n\n```javascript\nimport { createRequire } from 'https://deno.land/std@0.177.0/node/module.ts';\nconst require = createRequire(import.meta.url);\n\nconst mongoose = require('mongoose');\n\nmongoose.connect('mongodb://127.0.0.1:27017/test')\n  .then(() =\u003e console.log('Connected!'));\n```\n\nYou can then run the above script using the following.\n\n```sh\ndeno run --allow-net --allow-read --allow-sys --allow-env mongoose-test.js\n```\n\n## Mongoose for Enterprise\n\nAvailable as part of the Tidelift Subscription\n\nThe 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.](https://tidelift.com/subscription/pkg/npm-mongoose?utm_source=npm-mongoose\u0026utm_medium=referral\u0026utm_campaign=enterprise\u0026utm_term=repo)\n\n## Overview\n\n### Connecting to MongoDB\n\nFirst, 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`.\n\nBoth `connect` and `createConnection` take a `mongodb://` URI, or the parameters `host, database, port, options`.\n\n```js\nawait mongoose.connect('mongodb://127.0.0.1/my_database');\n```\n\nOnce 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`.\n\n**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.*\n\n**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.\n\n### Defining a Model\n\nModels are defined through the `Schema` interface.\n\n```js\nconst Schema = mongoose.Schema;\nconst ObjectId = Schema.ObjectId;\n\nconst BlogPost = new Schema({\n  author: ObjectId,\n  title: String,\n  body: String,\n  date: Date\n});\n```\n\nAside from defining the structure of your documents and the types of data you're storing, a Schema handles the definition of:\n\n* [Validators](http://mongoosejs.com/docs/validation.html) (async and sync)\n* [Defaults](http://mongoosejs.com/docs/api/schematype.html#schematype_SchemaType-default)\n* [Getters](http://mongoosejs.com/docs/api/schematype.html#schematype_SchemaType-get)\n* [Setters](http://mongoosejs.com/docs/api/schematype.html#schematype_SchemaType-set)\n* [Indexes](http://mongoosejs.com/docs/guide.html#indexes)\n* [Middleware](http://mongoosejs.com/docs/middleware.html)\n* [Methods](http://mongoosejs.com/docs/guide.html#methods) definition\n* [Statics](http://mongoosejs.com/docs/guide.html#statics) definition\n* [Plugins](http://mongoosejs.com/docs/plugins.html)\n* [pseudo-JOINs](http://mongoosejs.com/docs/populate.html)\n\nThe following example shows some of these features:\n\n```js\nconst Comment = new Schema({\n  name: { type: String, default: 'hahaha' },\n  age: { type: Number, min: 18, index: true },\n  bio: { type: String, match: /[a-z]/ },\n  date: { type: Date, default: Date.now },\n  buff: Buffer\n});\n\n// a setter\nComment.path('name').set(function(v) {\n  return capitalize(v);\n});\n\n// middleware\nComment.pre('save', function(next) {\n  notify(this.get('email'));\n  next();\n});\n```\n\nTake a look at the example in [`examples/schema/schema.js`](https://github.com/Automattic/mongoose/blob/master/examples/schema/schema.js) for an end-to-end example of a typical setup.\n\n### Accessing a Model\n\nOnce we define a model through `mongoose.model('ModelName', mySchema)`, we can access it through the same function\n\n```js\nconst MyModel = mongoose.model('ModelName');\n```\n\nOr just do it all at once\n\n```js\nconst MyModel = mongoose.model('ModelName', mySchema);\n```\n\nThe 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\n\n```js\nconst MyModel = mongoose.model('Ticket', mySchema);\n```\n\nThen `MyModel` will use the **tickets** collection, not the **ticket** collection. For more details read the [model docs](https://mongoosejs.com/docs/api/mongoose.html#mongoose_Mongoose-model).\n\nOnce we have our model, we can then instantiate it, and save it:\n\n```js\nconst instance = new MyModel();\ninstance.my.key = 'hello';\nawait instance.save();\n```\n\nOr we can find documents from the same collection\n\n```js\nawait MyModel.find({});\n```\n\nYou can also `findOne`, `findById`, `update`, etc.\n\n```js\nconst instance = await MyModel.findOne({ /* ... */ });\nconsole.log(instance.my.key); // 'hello'\n```\n\nFor more details check out [the docs](http://mongoosejs.com/docs/queries.html).\n\n**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:\n\n```js\nconst conn = mongoose.createConnection('your connection string');\nconst MyModel = conn.model('ModelName', schema);\nconst m = new MyModel();\nawait m.save(); // works\n```\n\nvs\n\n```js\nconst conn = mongoose.createConnection('your connection string');\nconst MyModel = mongoose.model('ModelName', schema);\nconst m = new MyModel();\nawait m.save(); // does not work b/c the default connection object was never connected\n```\n\n### Embedded Documents\n\nIn the first example snippet, we defined a key in the Schema that looks like:\n\n```txt\ncomments: [Comment]\n```\n\nWhere `Comment` is a `Schema` we created. This means that creating embedded documents is as simple as:\n\n```js\n// retrieve my model\nconst BlogPost = mongoose.model('BlogPost');\n\n// create a blog post\nconst post = new BlogPost();\n\n// create a comment\npost.comments.push({ title: 'My comment' });\n\nawait post.save();\n```\n\nThe same goes for removing them:\n\n```js\nconst post = await BlogPost.findById(myId);\npost.comments[0].deleteOne();\nawait post.save();\n```\n\nEmbedded documents enjoy all the same features as your models. Defaults, validators, middleware.\n\n### Middleware\n\nSee the [docs](http://mongoosejs.com/docs/middleware.html) page.\n\n#### Intercepting and mutating method arguments\n\nYou can intercept method arguments via middleware.\n\nFor example, this would allow you to broadcast changes about your Documents every time someone `set`s a path in your Document to a new value:\n\n```js\nschema.pre('set', function(next, path, val, typel) {\n  // `this` is the current Document\n  this.emit('set', path, val);\n\n  // Pass control to the next pre\n  next();\n});\n```\n\nMoreover, 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`:\n\n```js\nschema.pre(method, function firstPre(next, methodArg1, methodArg2) {\n  // Mutate methodArg1\n  next('altered-' + methodArg1.toString(), methodArg2);\n});\n\n// pre declaration is chainable\nschema.pre(method, function secondPre(next, methodArg1, methodArg2) {\n  console.log(methodArg1);\n  // =\u003e 'altered-originalValOfMethodArg1'\n\n  console.log(methodArg2);\n  // =\u003e 'originalValOfMethodArg2'\n\n  // Passing no arguments to `next` automatically passes along the current argument values\n  // i.e., the following `next()` is equivalent to `next(methodArg1, methodArg2)`\n  // and also equivalent to, with the example method arg\n  // values, `next('altered-originalValOfMethodArg1', 'originalValOfMethodArg2')`\n  next();\n});\n```\n\n#### Schema gotcha\n\n`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:\n\n```js\nnew Schema({\n  broken: { type: Boolean },\n  asset: {\n    name: String,\n    type: String // uh oh, it broke. asset will be interpreted as String\n  }\n});\n\nnew Schema({\n  works: { type: Boolean },\n  asset: {\n    name: String,\n    type: { type: String } // works. asset is an object with a type property\n  }\n});\n```\n\n### Driver Access\n\nMongoose is built on top of the [official MongoDB Node.js driver](https://github.com/mongodb/node-mongodb-native). Each mongoose model keeps a reference to a [native MongoDB driver collection](http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html). 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\nnotable exception that `YourModel.collection` still buffers\ncommands. As such, `YourModel.collection.find()` will **not**\nreturn a cursor.\n\n## API Docs\n\n[Mongoose API documentation](http://mongoosejs.com/docs/api/mongoose.html), generated using [dox](https://github.com/tj/dox)\nand [acquit](https://github.com/vkarpov15/acquit).\n\n## Related Projects\n\n### MongoDB Runners\n\n* [run-rs](https://www.npmjs.com/package/run-rs)\n* [mongodb-memory-server](https://www.npmjs.com/package/mongodb-memory-server)\n* [mongodb-topology-manager](https://www.npmjs.com/package/mongodb-topology-manager)\n\n### Unofficial CLIs\n\n* [mongoosejs-cli](https://www.npmjs.com/package/mongoosejs-cli)\n\n### Data Seeding\n\n* [dookie](https://www.npmjs.com/package/dookie)\n* [seedgoose](https://www.npmjs.com/package/seedgoose)\n* [mongoose-data-seed](https://www.npmjs.com/package/mongoose-data-seed)\n\n### Express Session Stores\n\n* [connect-mongodb-session](https://www.npmjs.com/package/connect-mongodb-session)\n* [connect-mongo](https://www.npmjs.com/package/connect-mongo)\n\n## License\n\nCopyright (c) 2010 LearnBoost \u0026lt;dev@learnboost.com\u0026gt;\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fautomattic%2Fmongoose","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fautomattic%2Fmongoose","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fautomattic%2Fmongoose/lists"}