Gathering detailed insights and metrics for mongoose
Gathering detailed insights and metrics for mongoose
Gathering detailed insights and metrics for mongoose
Gathering detailed insights and metrics for mongoose
mongoose-legacy-pluralize
Legacy pluralization logic for mongoose
@opentelemetry/instrumentation-mongoose
OpenTelemetry instrumentation for `mongoose` database object data modeling (ODM) library for MongoDB
egg-mongoose
egg mongoose plugin
@nestjs/mongoose
Nest - modern, fast, powerful node.js web framework (@mongoose)
MongoDB object modeling designed to work in an asynchronous environment.
npm install mongoose
Typescript
Module System
Min. Node Version
Node Version
NPM Version
JavaScript (94.72%)
TypeScript (5.1%)
Pug (0.13%)
Shell (0.04%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
MIT License
27,283 Stars
22,682 Commits
3,857 Forks
481 Watchers
142 Branches
988 Contributors
Updated on Jul 10, 2025
Latest Version
8.16.3
Package Id
mongoose@8.16.3
Unpacked Size
2.45 MB
Size
571.11 kB
File Count
301
NPM Version
10.8.2
Node Version
20.18.1
Published on
Jul 10, 2025
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
41
Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. Mongoose supports Node.js and Deno (alpha).
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.
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.
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.
First install Node.js and MongoDB. Then:
1npm install mongoose
Mongoose 6.8.0 also includes alpha support for Deno.
1// Using Node.js `require()` 2const mongoose = require('mongoose'); 3 4// Using ES6 imports 5import mongoose from 'mongoose';
Or, using Deno's createRequire()
for CommonJS support as follows.
1import { createRequire } from 'https://deno.land/std@0.177.0/node/module.ts'; 2const require = createRequire(import.meta.url); 3 4const mongoose = require('mongoose'); 5 6mongoose.connect('mongodb://127.0.0.1:27017/test') 7 .then(() => console.log('Connected!'));
You can then run the above script using the following.
1deno run --allow-net --allow-read --allow-sys --allow-env mongoose-test.js
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.
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
.
1await 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.
Models are defined through the Schema
interface.
1const Schema = mongoose.Schema; 2const ObjectId = Schema.ObjectId; 3 4const BlogPost = new Schema({ 5 author: ObjectId, 6 title: String, 7 body: String, 8 date: Date 9});
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:
1const Comment = new Schema({
2 name: { type: String, default: 'hahaha' },
3 age: { type: Number, min: 18, index: true },
4 bio: { type: String, match: /[a-z]/ },
5 date: { type: Date, default: Date.now },
6 buff: Buffer
7});
8
9// a setter
10Comment.path('name').set(function(v) {
11 return capitalize(v);
12});
13
14// middleware
15Comment.pre('save', function(next) {
16 notify(this.get('email'));
17 next();
18});
Take a look at the example in examples/schema/schema.js
for an end-to-end example of a typical setup.
Once we define a model through mongoose.model('ModelName', mySchema)
, we can access it through the same function
1const MyModel = mongoose.model('ModelName');
Or just do it all at once
1const 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
1const 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:
1const instance = new MyModel(); 2instance.my.key = 'hello'; 3await instance.save();
Or we can find documents from the same collection
1await MyModel.find({});
You can also findOne
, findById
, update
, etc.
1const instance = await MyModel.findOne({ /* ... */ }); 2console.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:
1const conn = mongoose.createConnection('your connection string'); 2const MyModel = conn.model('ModelName', schema); 3const m = new MyModel(); 4await m.save(); // works
vs
1const conn = mongoose.createConnection('your connection string'); 2const MyModel = mongoose.model('ModelName', schema); 3const m = new MyModel(); 4await m.save(); // does not work b/c the default connection object was never connected
In the first example snippet, we defined a key in the Schema that looks like:
1comments: [Comment]
Where Comment
is a Schema
we created. This means that creating embedded documents is as simple as:
1// retrieve my model 2const BlogPost = mongoose.model('BlogPost'); 3 4// create a blog post 5const post = new BlogPost(); 6 7// create a comment 8post.comments.push({ title: 'My comment' }); 9 10await post.save();
The same goes for removing them:
1const post = await BlogPost.findById(myId); 2post.comments[0].deleteOne(); 3await post.save();
Embedded documents enjoy all the same features as your models. Defaults, validators, middleware.
See the docs page.
You can intercept method arguments via middleware.
For 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:
1schema.pre('set', function(next, path, val, typel) { 2 // `this` is the current Document 3 this.emit('set', path, val); 4 5 // Pass control to the next pre 6 next(); 7});
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
:
1schema.pre(method, function firstPre(next, methodArg1, methodArg2) { 2 // Mutate methodArg1 3 next('altered-' + methodArg1.toString(), methodArg2); 4}); 5 6// pre declaration is chainable 7schema.pre(method, function secondPre(next, methodArg1, methodArg2) { 8 console.log(methodArg1); 9 // => 'altered-originalValOfMethodArg1' 10 11 console.log(methodArg2); 12 // => 'originalValOfMethodArg2' 13 14 // Passing no arguments to `next` automatically passes along the current argument values 15 // i.e., the following `next()` is equivalent to `next(methodArg1, methodArg2)` 16 // and also equivalent to, with the example method arg 17 // values, `next('altered-originalValOfMethodArg1', 'originalValOfMethodArg2')` 18 next(); 19});
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:
1new Schema({
2 broken: { type: Boolean },
3 asset: {
4 name: String,
5 type: String // uh oh, it broke. asset will be interpreted as String
6 }
7});
8
9new Schema({
10 works: { type: Boolean },
11 asset: {
12 name: String,
13 type: { type: String } // works. asset is an object with a type property
14 }
15});
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.
Mongoose API documentation, generated using dox and acquit.
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.
9.1/10
Summary
Mongoose search injection vulnerability
Affected Versions
< 6.13.6
Patched Versions
6.13.6
9.1/10
Summary
Mongoose search injection vulnerability
Affected Versions
>= 7.0.0-rc0, < 7.8.4
Patched Versions
7.8.4
9.1/10
Summary
Mongoose search injection vulnerability
Affected Versions
>= 8.0.0-rc0, < 8.9.5
Patched Versions
8.9.5
9.8/10
Summary
Mongoose Vulnerable to Prototype Pollution in Schema Object
Affected Versions
< 5.13.15
Patched Versions
5.13.15
9.8/10
Summary
Mongoose Vulnerable to Prototype Pollution in Schema Object
Affected Versions
>= 6.0.0, < 6.4.6
Patched Versions
6.4.6
9.1/10
Summary
Improper Input Validation in Automattic Mongoose
Affected Versions
< 4.13.21
Patched Versions
4.13.21
9.1/10
Summary
Improper Input Validation in Automattic Mongoose
Affected Versions
>= 5.0.0, < 5.7.5
Patched Versions
5.7.5
10/10
Summary
Mongoose Prototype Pollution vulnerability
Affected Versions
< 5.13.20
Patched Versions
5.13.20
10/10
Summary
Mongoose Prototype Pollution vulnerability
Affected Versions
>= 6.0.0, < 6.11.3
Patched Versions
6.11.3
10/10
Summary
Mongoose Prototype Pollution vulnerability
Affected Versions
>= 7.0.0, < 7.3.3
Patched Versions
7.3.3
9.8/10
Summary
Mongoose search injection vulnerability
Affected Versions
< 6.13.5
Patched Versions
6.13.5
9.8/10
Summary
Mongoose search injection vulnerability
Affected Versions
>= 7.0.0-rc0, < 7.8.3
Patched Versions
7.8.3
9.8/10
Summary
Mongoose search injection vulnerability
Affected Versions
>= 8.0.0-rc0, < 8.8.3
Patched Versions
8.8.3
7/10
Summary
automattic/mongoose vulnerable to Prototype pollution via Schema.path
Affected Versions
< 5.13.15
Patched Versions
5.13.15
7/10
Summary
automattic/mongoose vulnerable to Prototype pollution via Schema.path
Affected Versions
>= 6.0.0, < 6.4.6
Patched Versions
6.4.6
5.1/10
Summary
Remote Memory Exposure in mongoose
Affected Versions
>= 4.0.0, <= 4.3.5
Patched Versions
4.3.6
5.1/10
Summary
Remote Memory Exposure in mongoose
Affected Versions
>= 3.5.5, <= 3.8.38
Patched Versions
3.8.39
Reason
30 commit(s) and 23 issue activity found in the last 90 days -- score normalized to 10
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
0 existing vulnerabilities detected
Reason
security policy file detected
Details
Reason
Found 7/8 approved changesets -- score normalized to 8
Reason
SAST tool detected but not run on all commits
Details
Reason
dependency not pinned by hash detected -- score normalized to 2
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
project is not fuzzed
Details
Score
Last Scanned on 2025-07-07
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More