npm / mongoose
mongoose
What changed in mongoose 6 to 9, from its official release notes, upgrade guides and advisories. Sources checked 2026-12-05.
48 breaking11 security1 deprecations33 new APIs and options17 performance19 behavior and defaults183 fixes and other
See which of these apply to your code, ranked, in your agent:
npx @unstale/cli initmongoose 9272 changes
Breaking changes 43
Catches top-level filter fields starting with $ to prevent bypasses using MongoDB internal expressions.
The unused use$geoWithin property was removed.
Special properties such as __proto__ are disallowed as paths in mod().
Setting special properties via virtual() is disallowed.
Special properties such as __proto__ are disallowed as paths in where().
Removing a path now also drops its subpaths and singleNestedPaths.
Removing a map path also drops its values subpath, and removes maps that live under nested paths.
Casting to Double now rejects arrays.
Casting to Int32 now rejects arrays.
Queries now reject update modifiers without paths.
Empty document array elements are no longer minimized to null.
Schematype lookups return only own properties, and setting schema paths under special properties is disallowed.
Throws an error when overwriting an array selected with
$slice.Removes the union fallback from
validateSync().insertOne() throws ObjectParameterError when the document argument is not an object.
Reverts running setters on default values during upsert.
TypeScript now reports an error when $and contains an unrecognized query operator.
Makes MergeType distributive over union types.
Retains populated paths in the result type unless depopulate: true is set.
Schema type errors now use MongooseError instead of plain Error, allowing developers to handle them consistently.
Setting null or undefined as options now throws an error.
Removes the dead GeoSearch type.
Removes the dead MapReduce type.
Inference no longer adds _id to nested paths and handles _id: false in options and schema definitions.
The browser build is removed; browser support moves to @mongoosejs/browser.
bson is no longer a direct dependency; use mongodb/lib/bson instead.
The casterConstructor property is removed in favor of embeddedSchemaType and Constructor.
The TypeScript parameters for create() are stricter, and its generics are removed to prevent type inference.
The TypeScript this type for default() changes to HydratedDocument.
FilterQuery properties no longer resolve to any in TypeScript.
findOne(null) and similar calls now throw an error instead of returning the first document.
In TypeScript, id is now a virtual rather than a property on the Document base class.
The TypeScript parameters for insertOne() are stricter, and its generics are removed to prevent type inference.
Mongoose updates to MongoDB Node driver v7, which may affect applications relying on driver behavior.
Browser support is moved to the @mongoosejs/browser package.
The connection noListener option is removed.
Callback-based pre middleware, including calling next() in pre() hooks, is no longer supported.
The TypeScript this type for required() changes to HydratedDocument.
The schematype caster property is removed in favor of embeddedSchemaType and Constructor.
Update pipelines are disallowed by default; enable them with the updatePipeline option.
The UUID schema type now returns BSON UUIDs.
validate() is now an async function, and Kareem hooks are called directly rather than through wrappers.
Virtual ref functions are called with the subdocument instead of the top-level document.
Security 9
Hardens sanitizeProjection.
Mongoose: Connection-level sanitizeFilter not applied
Mongoose: Discriminator key values matching inherited properties (e.g. __t: 'constructor') bypass schema casting and can poison collections
Mongoose walks into inherited properties when hydrating, setting, and merging, allowing overwrites of built-in functions (denial of service) and shared schema state
cursor() now applies sanitizeFilter.
Mongoose: sanitizeFilter not applied on countDocuments
Avoids returning inherited properties from schema path lookups.
Mongoose's Improper Sanitization of $nor in sanitizeFilter May Allow NoSQL Injection
sanitizeFilter now handles other top-level query operators.
Deprecations 1
Adds $getChanges() as an alias for getChanges(), which is deprecated.
New APIs and options 28
Adds Query.prototype.findAndCount() for composable paginated queries.
Adds a wrapper for limit-and-skip-based pagination with countDocuments.
Adds a method to make it easier to define query helpers in TypeScript.
Supports a middleware skip option for cursors and custom hooks.
Adds pathsToSave to the SaveOptions type.
Adds a schema option to filter or throw on unknown fields during document hydration.
Adds a standard schema adapter for models.
Adds Node.js TracingChannel support for APM instrumentation.
Adds
$percentileto TypeScript aggregation expression types.Exports ArrayProjectionOperators for use in TypeScript code.
Exports Projector for use in TypeScript code.
Adds the allowNull option to disallow null values even when a schema path is not required.
Adds a timestamp option to debug output.
Extends the defaults query option to find().
Adds an option to explicitly disable update cloning.
Implements validation for Union schemas and subdocuments.
Supports the discriminators option inline for better TypeScript support.
Adds a helper for reusing pipelines with $unionWith in TypeScript.
An option was added to skip middleware.
Adds a strict option to Model.hydrate(...).
Adds the flattenUUIDs option to toObject() and toJSON().
DocumentArrayElement is exposed for use by developers.
Allows calling create() with TRawDocType for better generics support.
Adds getAtomics() support so custom container types can utilize atomics.
Adds an exclude option for optimistic concurrency.
Adds support for TypeScript-style enums.
Exports a type that replicates Mongoose 8 InferRawDocType behavior.
Schema.create() is added to support TypeScript type inference.
Performance 16
Avoid quadratic concat() when creating a MongooseMap from an object.
Improves performance for document arrays by caching paths with defaults and schemas with select paths, and avoiding unnecessary $isModified() lookups.
Makes MergeType more efficiently handle MergeType<A, {}>.
Avoids applying saveSubdocs and sharding plugins to subdocuments.
Projection metadata is cached, and flat projections avoid scanning all projected paths.
Improves general change tracking performance.
Avoids adding $setOnInsert for createdAt unless upsert is set.
Improves insertMany() performance.
Improves toObject performance with faster string checks and by avoiding unnecessary isSelected checks on paths with no getters.
Improves save performance by avoiding unnecessary promise allocations and reducing path, default, and dirty-state overhead.
Removes an unnecessary clone in findOneAndUpdate().
Removes unnecessary overhead when saving a new document.
Indexed-path checks for subdocuments are optimized.
pathsToSave is optimized for subdocuments.
Selects only _id when checking document existence during save(), improving performance.
Buffer comparison uses native Buffer.equals() for improved performance.
Behavior and default changes 17
Int32 paths are now treated as number in schema types.
Adds type narrowing when using projection in find and findOne.
Custom cast error messages from document validation now replace {MODEL}.
Includes id among HydratedDocument virtuals by default unless explicitly set.
Runs setters on default values during upsert.
Supports generating JSON Schema for unions.
Makes UnpackedIntersection distributive over union types.
Default functions now receive the query as their context.
Types allow unknown keys in subdocuments while retaining autocomplete suggestions.
The warning is delayed until createIndexes runs so it can include the model name.
Adds the id virtual getter by default when TOverrides is Record<string, never>.
Can handle saving just a subpath of a modified path.
Passes update and options to pre('updateOne') hooks.
Save hooks are asyncified for improved stack traces.
SchemaType.prototype.doValidate() is asyncified for improved stack traces.
Update validators are asyncified for improved stack traces.
The TypeScript this type for validate() changes to HydratedDocument | Query.
Fixes and other changes 158
Avoids converting BigInts to numbers when using addToSet().
Casts $and, $or, and $nor wherever they appear in an array filter.
Propagates an error passed to destroy() without re-emitting it if the error was already emitted.
Throws cast errors and respects the strict option in replaceOne().
Setting dotted paths at least three levels deep underneath single nested subdocuments is now allowed.
Resets document state before retrying after a transient commit error.
Subdocuments pushed via array filters receive timestamps.
Cursor destruction finishes after terminal initialization.
Calling push() again with $each keeps values that were pushed earlier.
Validates paths under a nested path passed to Model.validate().
Skips array-level validators for $pull with $in.
Cloned queries handle inherited read preference and read concern.
Cloned queries handle inherited read preference and read concern.
Compares UUIDs by value so pull() and addToSet() work.
Recomputes derived caches and delays _preCompile() until an actual model is compiled, rather than for subdocuments or document arrays.
autoCreate is no longer disabled for a primary ReadPreference instance.
autoIndex is no longer disabled for a primary ReadPreference instance.
Model.validate() no longer crashes when nested objects are missing.
Upserts and nested timestamps now honor overwriteImmutable.
Casts array filter values in bulkWrite().
Allows function messages for number min/max and string minlength validators.
Array filters continue to be cast after a path not in the schema.
Filters selecting a discriminator key with $eq or $in now use the embedded discriminator schema.
flattenDecimals is now applied when toObject() takes the shallow fast path.
Initializing nested document arrays no longer passes arrayPathIndex to subdocuments.
Operators under $not inside $elemMatch on primitive arrays are now cast.
Destroying query cursors now awaits driver cleanup.
Setting a path to a nested object now calls recursive toObject().
UpdateManyModel update typing is now aligned with UpdateQuery.
UpdateOneModel update typing is now aligned with UpdateQuery.
Avoids double-calling validators on document arrays underneath nested paths.
Passes TLeanResultType into query for type narrowing support with lean().
Handle MongoDB server 9.x returning collation: { locale: 'simple' } on all indexes.
Compare dates by value in indexOf() so pull() removes them.
Register $set when Map#set() replaces an array.
Resolve dotted parent paths when collecting deferred sub-populate children.
Cast case and then expressions in $expr $switch branches.
Preserves unsaved documents after ordered bulkSave errors.
Avoids mutating the caller's update object in bulkWrite updateMany.
Replaces {MODEL} in cast error messages from update and bulkWrite casting.
Opens the collection when the connection was already opened.
Setters declared on the union path itself now run.
Cast error messages from castObject now replace {MODEL}.
Cloning with a seen map now preserves circular arrays.
Path-level setters are now registered on Map paths.
Relaxes Model generics so typed virtuals can be passed to populate in TypeScript 7 with skipLibCheck.
Defaults are now applied to undefined array elements.
The method's return type now includes the new static.
Correctly builds the dotted path when checking inclusive path selection.
Adds missing properties to the return type, improving the type information available to callers.
The schema is now passed through when casting a nested comparison.
Indexes bulkSave write errors by document id.
Cloned document array elements retain their own constructor signature.
Clarifies that a duplicate index warning means the index is not created.
Cloning keeps the map value schematype as a single object.
Reference lookup during hydration now uses the document's model.
Avoids repeating null in an enum when the enum already lists null.
bulkSave() sets the document session so transaction retries restore document state.
The optimistic concurrency paths option now supports map wildcards.
toJSONSchema() puts enum on array elements and supports the object enum form.
Types now respect schema toObject and toJSON options.
Delete state is restored across transaction retries.
Types now support overriding schema-level lean with lean: false.
Avoids path collisions when excluding subdocuments that have nested select: false paths.
Adds the discriminator key to each member of the embedded discriminator enum.
Model.schema remains typed when TSchema is omitted.
StandardSchema type inference now respects the _id option.
Avoids mutating shared setters when casting array query values.
Correctly handles version keys when bulkSave() inserts new documents.
Types now support extra fields in hydrate() when strict: false.
Correctly casts object-shaped geo query values.
Correctly handles excluded parent paths with optimistic concurrency.
Fixes TypeScript handling of nested objects typed as interfaces when using create.
Corrects TypeScript handling of the this parameter for methods when versionKey is used.
Corrects the return type of Model.validate() to Promise<TRawDocType>.
Reindexes subdocuments after array reordering and removal so subsequent nested changes save using the correct path.
Avoids accessing special properties in Document.prototype.get().
Runs separate populate queries per document when the resulting $in filter has more than 50k elements, reducing the risk of BSON size errors.
Includes the ObjectId regex pattern in toJSONSchema() output.
Aggregation middleware no longer waits on buffering to run.
Primitive types within unions are cast when applying create casting.
Cloned arrays are isolated from source documents.
Error validators receive the raw string value; trimming to 30 characters is limited to the maxlength validator.
Preserves a user-provided value when
overwriteImmutable: trueis used.Handles compiling with the exactOptionalPropertyTypes TypeScript option.
Correctly handles modified subpaths when the parent path is unset after modifying.
Fixes the
_idgetter helper on ObjectId.QueryFilter types now respect string unions and enums.
Preserves the reason in the CastError message after setModel().
Query helpers now pass default options to discriminators.
Fixes handling of included and excluded nested paths with optimistic concurrency.
Casting updates no longer treats documents with a $set() method as objects with a $set property.
Updates are cloned only when absolutely necessary, improving support for updates with __proto__.
Snapshots Date values in the heartbeat handler and flushes the queue on recovery.
Compares Set objects properly.
Corrects the error reported for an unsupported query operator with a number.
Validates that the argument is actually a connection using duck-typing with a version check.
MergeType is distributive, improving populate type support for models whose hydrated document type is a union.
castNumber replaces assert.ok with a descriptive Error.
Connection errors use MongooseError instead of Error.
Query errors use MongooseError instead of Error.
Query filter cast errors now include the array value in the error message, making failures easier to diagnose.
Fixes sorting in bulkWrite().
Passing a string projection to hydrate() is now handled correctly.
Fixes the type definition for HydratedDocType in autoTypedVirtuals.
The QueryCursor close callback now has the correct this context.
Schema options are now inferred correctly for model context in statics.
Schema.prototype.plugin() now allows passing a model with custom TStatics.
Resolves deeply nested discriminator paths in arrayFilters.
Emits ready on the next tick, allowing the stream to initialize.
Adds type constraints for Document#$model() and Document#model().
Falls back to InferRawDocType instead of pulling a non-raw inferred document type when EnforcedDocType is not set.
Avoids a TypeError when handling a nullish update.
Makes validateBeforeSave handling backwards compatible.
Handles calling watch() on a disconnected connection.
Fixes type issues when defining timestamps and virtuals with methods and/or statics in schema options.
Corrects the type signature so bulkSave() takes an array of THydratedDocumentType.
The document pathsToSave filter now handles all update operators and preserves unsaved state.
refPath now works as a function, including on map paths with $*.
Checks child filter paths before applying defaults.
Allows assigning QueryFilter<DocType> to QueryFilter<any>.
Preserves subdocument toObject() field types when using virtuals and versionKey options.
Fixes a duplicate identifier in mongoosejs 9.2.0.
An undefined id option is treated as not provided.
An undefined strict option is treated as not provided.
An undefined strictQuery option is treated as not provided.
Correctly clones a subdocument when updating a document array.
Fixes change tracking for document arrays stored in nested maps.
Subpopulation is deferred until after match functions, avoiding comparisons against populated subdocuments.
Fixes toObject() type inference when timestamps and virtuals are used.
Corrects type inference handling for subdocuments and document arrays.
Map subdocuments are validated when loaded with init.
Prevents indexes and callQueue duplication when schemas are shared as nested schemas.
Cloning map and array subdocuments now fixes their parent document reference.
Documents retrieved by a cursor now have sessions attached.
hydrate() now handles nested schema arrays.
Accessing nested paths on a prototype no longer crashes.
The timestamps option supports both boolean and QueryTimestampsConfig values when using insertMany().
Basic type casting is applied to paths underneath subdocuments.
Errors when merging a normal update with a pipeline include previews of the current and incoming updates.
Correctly handles PopulatedDoc and other TypeScript unions with Document members.
Passes options to pre-save hooks for subdocuments.
Avoids 'Cannot mix array and object updates' when using doc.updateOne() with a pipeline.
The filter property supports Mongoose query casting in its types.
Passes options to pre('deleteOne') hooks.
Triggers the error post hook when a pre-hook throws an error during bulkWrite.
Correctly infers virtuals and methods from schema options.
Applies Mongoose casting to the default MongoDB driver _id in RootFilterOperators.
Fixes detection of the this parameter type for methods with arguments.
Accumulates version mode flags using bitwise OR.
Passes the overwriteImmutable option to castUpdate in bulkWrite.
Clears timeouts in collection operations.
Fixes an incorrect variable bug in double casting.
Adds the enumValues property to Number enums for consistency with String enums.
Fixes overwriteImmutable with timestamps: true and adds types for overwriteImmutable.
Uses function overrides instead of | Query<any, any> to support using Query as a filter.
Missing pluralizations are added and existing pluralization is fixed, including virus to viruses.
RootQuerySelector, Condition, and related types are consolidated with the MongoDB driver's types.
mongoose 831 changes
Breaking changes 3
cursor() now applies sanitizeFilter.
Schema path lookups no longer return inherited properties, including for paths underneath maps of subdocuments.
Defaults the _id type to ObjectId for Document.
Security 1
Prototype pollution through query helpers such as gt() and in() is avoided.
New APIs and options 3
Supports the sort option in updateOne and replaceOne operations passed to Model.bulkWrite().
hydrate() now accepts a strict option, allowing developers to control strict behavior when hydrating documents.
Documents now include toBSON() in their types.
Performance 1
Avoids computing all modified paths when running setDefaultsOnInsert and update validators; paths are calculated only if there are defaults to set.
Behavior and default changes 1
Passes the parent schema to SchemaType constructors, making it easier to implement custom container types.
Fixes and other changes 22
A primary ReadPreference instance no longer disables autoIndex or autoCreate.
Removing map paths now works cleanly, including maps under nested paths.
MongooseMap.has() now supports ObjectId keys.
Query path collisions are avoided when excluding a subdocument that has a select: false child.
Reindex subdocuments when addToSet() skips a duplicate.
Bulk write updates now respect the schema currentTime option.
When cloning a document with subdocuments, the subdocuments now have the cloned document as their parent.
After a successful doc.deleteOne(), $isDeleted is now set.
Paths with default: null are no longer treated as required in schema types.
Improves the error when Document.prototype.init() is called with null or undefined.
Allows partial statics to be passed to schema.statics().
Mongoose now bumps the version if necessary after a successful bulkSave().
Type definitions now allow calling schema.static() with as TStatics.
Corrects the Model.schema type and fixes the unknown check for this parameter type in schema.methods, improving TypeScript type checking.
Casts the id parameter based on the schema _id type.
Avoids throwing an error when a schema contains an array of unions.
Corrects the return type of discriminator to Model<U>.
Validation errors now store the original index of the document in the insertMany input.
Correctly applies the shard key when calling deleteOne().
Correctly infers the empty array type [] as any[].
Correctly caches text indexes as 'text' rather than 1.
Corrects handling of relative versus absolute paths with maps and subdocuments.
mongoose 75 changes
Breaking changes 1
Schema options are copied when merging schemas with new Schema() or Schema.prototype.add().
Security 1
sanitizeFilter is now applied in countDocuments and cursor.
New APIs and options 1
MongoDB types are exported more robustly.
Behavior and default changes 1
Allows merging single nested paths and document array paths outside discriminator schema merges.
Fixes and other changes 1
Adds defensive checks for special properties when getting values from a document.
mongoose 64 changes
Breaking changes 1
The deprecated safe option was removed in favor of write concerns.
New APIs and options 1
Adds aggregate operator types for $firstN, $lastN, $bottom, $bottomN, $minN and $maxN.
Fixes and other changes 2
countDocuments() can now be called with options.
$parent() is used as a getter function for a subdocument's parent.