mongoose
semver
>=5.0.0postconditions69functions41last verified2026-06-23coverage score93%Postconditions — what we check
- find · connection-error-no-try-catcherrorWhenDatabase connection failed or was interruptedThrows
MongooseError or MongoErrorRequired handlingCaller MUST wrap in try-catch or use .catch(). Handle connection errors separately from query results. Implement retry logic for transient connection issues.costhighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[1] - find · cast-error-no-try-catcherrorWhenQuery parameter cannot be cast to expected typeThrows
CastErrorRequired handlingCaller MUST wrap in try-catch or use .catch(). Validate query parameters before passing to mongoose. Handle CastError separately from other errors.costhighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[2] - findOne · connection-error-no-try-catcherrorWhenDatabase connection failedThrows
MongooseError or MongoErrorRequired handlingCaller MUST wrap in try-catch or use .catch() to handle connection errorscosthighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[1] - findOne · cast-error-no-try-catcherrorWhenQuery parameter casting failedThrows
CastErrorRequired handlingCaller MUST wrap in try-catch to handle type casting errorscosthighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[3] - findById · cast-error-no-try-catch-invalid-iderrorWhenProvided ID is not a valid ObjectId formatThrows
CastError with kind: 'ObjectId'Required handlingCaller MUST wrap in try-catch or use .catch(). Common when user input is passed directly as ID. Validate ID format before querying.costhighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[4] - findById · connection-error-no-try-catcherrorWhenDatabase connection failedThrows
MongooseErrorRequired handlingCaller MUST handle connection errorscosthighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[1] - create · validation-error-no-try-catcherrorWhenDocument validation failed (missing required fields, wrong types, custom validators)Throws
ValidationError with errors object containing field-specific ValidatorErrorsRequired handlingCaller MUST wrap in try-catch or use .catch(). Check error.name === 'ValidationError' and inspect error.errors object. Each field error is accessible via error.errors[fieldName].costhighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[5] - create · duplicate-key-error-no-try-catcherrorWhenUnique constraint violation (E11000 error)Throws
MongoError with code: 11000Required handlingCaller MUST wrap in try-catch and check error.code === 11000. This is NOT a ValidationError - it comes from MongoDB driver. Extract duplicate field from error message or error.keyPattern.costhighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[6] - create · connection-error-no-try-catcherrorWhenDatabase connection failedThrows
MongooseErrorRequired handlingCaller MUST handle connection errors with retry logiccosthighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[1] - insertMany · validation-error-no-try-catcherrorWhenOne or more documents fail validationThrows
ValidationErrorRequired handlingCaller MUST wrap in try-catch. Default behavior stops on first error; use ordered:false to continue on errors.costhighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[7] - insertMany · duplicate-key-error-no-try-catcherrorWhenDuplicate key constraint violationThrows
MongoError with code: 11000Required handlingCaller MUST wrap in try-catch and handle duplicate key errorscosthighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[7] - updateOne · validation-error-no-try-catcherrorWhenUpdate violates validation rulesThrows
ValidationErrorRequired handlingCaller MUST wrap in try-catch to handle validation errorscosthighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[5] - updateOne · cast-error-no-try-catcherrorWhenUpdate value cannot be cast to schema typeThrows
CastErrorRequired handlingCaller MUST wrap in try-catch to handle type errorscosthighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[3] - updateOne · connection-error-no-try-catcherrorWhenDatabase connection failedThrows
MongooseErrorRequired handlingCaller MUST handle connection errorscosthighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[1] - findByIdAndUpdate · prototype-pollution-cve-2023-3696-no-try-catcherrorWhenMalicious update payload exploits prototype pollution vulnerabilityThrows
May not throw - vulnerability allows arbitrary code executionRequired handlingCaller MUST wrap in try-catch. CRITICAL: Ensure mongoose version >= 5.13.20, 6.4.6, or 7.3.1 to patch CVE-2023-3696. Validate and sanitize all update payloads from user input.costhighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[8] - findByIdAndUpdate · validation-error-no-try-catcherrorWhenUpdate violates validation rulesThrows
ValidationErrorRequired handlingCaller MUST wrap in try-catchcosthighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[5] - findByIdAndUpdate · cast-error-no-try-catcherrorWhenInvalid ObjectId or type casting failureThrows
CastErrorRequired handlingCaller MUST wrap in try-catchcosthighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[9] - findOneAndUpdate · prototype-pollution-cve-2023-3696-no-try-catcherrorWhenVulnerable to prototype pollution attacksThrows
May not throw - allows RCERequired handlingCaller MUST wrap in try-catch and validate input. Upgrade mongoose to patched version.costhighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[8] - findOneAndUpdate · validation-error-no-try-catcherrorWhenUpdate violates validationThrows
ValidationErrorRequired handlingCaller MUST wrap in try-catchcosthighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[5] - deleteOne · connection-error-no-try-catcherrorWhenDatabase connection failedThrows
MongooseErrorRequired handlingCaller MUST wrap in try-catchcosthighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[1] - findByIdAndDelete · cast-error-no-try-catcherrorWhenInvalid ObjectId formatThrows
CastErrorRequired handlingCaller MUST wrap in try-catchcosthighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[10] - findByIdAndDelete · connection-error-no-try-catcherrorWhenDatabase connection failedThrows
MongooseErrorRequired handlingCaller MUST wrap in try-catchcosthighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[1] - save · validation-error-no-try-catcherrorWhenDocument validation failedThrows
ValidationError with errors objectRequired handlingCaller MUST wrap in try-catch. Most common error when saving documents. Inspect error.errors for field-specific validation failures.costhighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[11] - save · duplicate-key-error-no-try-catcherrorWhenUnique constraint violationThrows
MongoError with code: 11000Required handlingCaller MUST wrap in try-catch and check error.code === 11000. Common when saving new documents with existing unique field values.costhighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[6] - save · connection-error-no-try-catcherrorWhenDatabase connection failedThrows
MongooseErrorRequired handlingCaller MUST wrap in try-catchcosthighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[1] - exec · query-error-no-try-catcherrorWhenQuery execution failedThrows
MongooseError, CastError, or ValidationError depending on failure typeRequired handlingCaller MUST wrap in try-catch or use .catch(). .exec() is the terminal operation for query chains. All query errors surface here.costhighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[12] - orFail · document-not-found-no-try-catcherrorWhenNo documents match the queryThrows
DocumentNotFoundErrorRequired handlingCaller MUST wrap in try-catch. .orFail() is explicitly designed to throw when no results found. Use this when document existence is mandatory.costhighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[13] - connect · connection-failed-no-try-catcherrorWhenCannot connect to MongoDB (network, auth, or invalid connection string)Throws
MongooseError or MongoErrorRequired handlingCaller MUST wrap in try-catch. Connection failures should stop application startup. Log error details and exit gracefully.costhighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[1] - aggregate · aggregation-error-no-try-catcherrorWhenInvalid pipeline stage or aggregation failureThrows
MongooseError or MongoErrorRequired handlingCaller MUST wrap in try-catch. Aggregation pipelines can fail with complex stage errors.costhighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[14] - countDocuments · connection-error-no-try-catcherrorWhenDatabase connection failedThrows
MongooseErrorRequired handlingCaller MUST wrap in try-catchcosthighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[15] - updateMany · connection-error-no-try-catcherrorWhenDatabase connection failedThrows
MongooseErrorRequired handlingCaller MUST wrap in try-catchcosthighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[16] - replaceOne · connection-error-no-try-catcherrorWhenDatabase connection failedThrows
MongooseErrorRequired handlingCaller MUST wrap in try-catchcosthighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[17] - findOneAndReplace · connection-error-no-try-catcherrorWhenDatabase connection failedThrows
MongooseErrorRequired handlingCaller MUST wrap in try-catchcosthighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[18] - deleteMany · connection-error-no-try-catcherrorWhenDatabase connection failedThrows
MongooseErrorRequired handlingCaller MUST wrap in try-catchcosthighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[19] - findOneAndDelete · connection-error-no-try-catcherrorWhenDatabase connection failedThrows
MongooseErrorRequired handlingCaller MUST wrap in try-catchcosthighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[20] - estimatedDocumentCount · connection-error-no-try-catcherrorWhenDatabase connection failedThrows
MongooseErrorRequired handlingCaller MUST wrap in try-catchcosthighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[21] - exists · connection-error-no-try-catcherrorWhenDatabase connection failedThrows
MongooseErrorRequired handlingCaller MUST wrap in try-catchcosthighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[22] - distinct · connection-error-no-try-catcherrorWhenDatabase connection failedThrows
MongooseErrorRequired handlingCaller MUST wrap in try-catchcosthighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[23] - bulkWrite · connection-error-no-try-catcherrorWhenDatabase connection failed or bulk operation errorThrows
MongooseError or BulkWriteErrorRequired handlingCaller MUST wrap in try-catchcosthighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[24] - validate · validation-error-no-try-catcherrorWhenDocument fails schema validationThrows
ValidationErrorRequired handlingCaller MUST wrap in try-catch. ValidationError contains field-specific errors.costhighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[25] - bulkSave · bulksave-validation-error-no-try-catcherrorWhenAny provided document fails Mongoose schema validation. bulkSave() halts BEFORE sending the bulkWrite() to MongoDB and throws the FIRST validation error encountered. No documents are written.Throws
ValidationError with errors object (same structure as Document.validate())Required handlingCaller MUST wrap in try-catch. Validate all documents before calling bulkSave() if partial-write is unacceptable — bulkSave() aborts on first validation error without writing any documents. Check error.name === 'ValidationError' and inspect error.errors.costhighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[26] - bulkSave · bulksave-document-not-found-no-try-catcherrorWhenbulkWrite() completes but inserts or updates ZERO documents (all operations were no-ops). Throws MongooseBulkSaveIncompleteError (a subclass of DocumentNotFoundError). Does NOT throw if only some operations succeeded.Throws
MongooseBulkSaveIncompleteError (extends DocumentNotFoundError)Required handlingCaller MUST wrap in try-catch. This is a silent-failure trap: if you update 10 documents and none match, bulkSave() throws. If 5 of 10 match, it silently returns without error. Use countDocuments() afterward to verify expected write counts if partial write correctness is critical.costhighin prodimmediate exceptionusers seelost datavisibilitysilentSources[26] - bulkSave · bulksave-duplicate-key-error-no-try-catcherrorWhenbulkWrite() fails due to a unique constraint violation (MongoDB E11000 duplicate key error) or a connection/network failure. The entire bulkWrite() round trip fails.Throws
MongoError with code: 11000 for duplicate key, or MongooseError for connection failureRequired handlingCaller MUST wrap in try-catch. Check error.code === 11000 for duplicate key violations. Unlike insertMany(ordered: false), bulkSave() with duplicate key errors does not continue — the entire batch fails.costhighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[26] - populate · populate-strict-populate-error-no-try-catcherrorWhenAttempting to populate a path that does not exist in the schema when strictPopulate is true (the default). Throws StrictPopulateError. Common when using populate() with dynamic path names or after schema changes that remove fields.Throws
StrictPopulateError (extends MongooseError)Required handlingCaller MUST wrap in try-catch. Check error.name === 'StrictPopulateError'. Either fix the path name to match the schema, or set { strictPopulate: false } in populate options if intentionally populating non-schema paths (e.g., in migration scripts).costmediumin prodimmediate exceptionusers seelost datavisibilityvisible - populate · populate-cast-error-no-try-catcherrorWhenThe localField value cannot be cast to the foreignField schema type. For example, populating a ref field that contains a string when the referenced model's _id is ObjectId.Throws
CastError (unless skipInvalidIds: true option is set)Required handlingCaller MUST wrap in try-catch. Use skipInvalidIds: true in populate options to filter out un-castable values instead of throwing. Check error.name === 'CastError' and error.path to identify the problematic field.costmediumin prodimmediate exceptionusers seelost datavisibilityvisibleSources[27] - populate · populate-connection-error-no-try-catcherrorWhenDatabase connection fails while fetching referenced documents. populate() issues additional queries to the database for each populated path — each query can fail independently.Throws
MongooseError or MongoErrorRequired handlingCaller MUST wrap in try-catch. Implement retry logic for transient connection failures. Consider caching populated results to reduce round trips.costhighin prodimmediate exceptionusers seelost datavisibilityvisibleSources[28] - transaction · transaction-abort-error-no-try-catcherrorWhenThe transaction function throws a non-transient error, or MongoDB cannot commit the transaction (network partition, write conflict, session timeout). The promise rejects with the error. Mongoose automatically resets all document state (isNew flags, modified paths) when a transaction aborts, but the caller is responsible for handling the rejection.Throws
MongoError or any error thrown by the transaction functionRequired handlingCaller MUST wrap in try-catch or use .catch(). After catching a transaction error, do NOT assume any document writes succeeded — the entire transaction was rolled back. Do NOT manually call session.abortTransaction() — connection.transaction() handles abort automatically via withTransaction(). Re-check document.isNew after an aborted transaction as Mongoose resets it to true.costhighin prodimmediate exceptionusers seelost datavisibilityvisible - transaction · transaction-parallel-operations-undefined-behaviorerrorWhenUsing Promise.all(), Promise.allSettled(), or Promise.race() to run operations in parallel within a single transaction. The Mongoose documentation explicitly states this is "undefined behaviour and should be avoided."Throws
Undefined — may succeed, may corrupt data, may throw intermittentlyRequired handlingALL operations within a transaction MUST be sequential (await each one individually). Do NOT use Promise.all() inside a transaction function. Parallel operations on the same session cause undefined behavior that is non-deterministic and environment-specific.costhighin prodsilent failureusers seelost datavisibilitysilentSources[29] - disconnect · disconnect-error-no-try-catchwarningWhenOne or more connections fail to close cleanly (e.g., network issue during close, driver error). The promise rejects with the first error encountered. Remaining connections may or may not be closed.Throws
MongooseError or MongoErrorRequired handlingCaller MUST wrap in try-catch or use .catch() during graceful shutdown. In process shutdown handlers (SIGTERM/SIGINT), ensure disconnect() errors are logged even if ignored — silent disconnect failures can leave connections open and cause process hang. Always call disconnect() in a finally block to ensure it runs even if other shutdown steps fail.costmediumin prodimmediate exceptionusers seeservice unavailablevisibilitysilentSources[31] - insertOne · insertone-validation-error-no-try-catcherrorWhenThe document fails schema validation (required field missing, type mismatch, custom validator rejection). insertOne() calls $save() internally which runs the full validation pipeline.Throws
ValidationErrorRequired handlingCaller MUST wrap in try-catch. Check error.name === 'ValidationError' and inspect error.errors for field-specific errors. Pre-validate with doc.validate() if you want to collect all errors before attempting the insert.costhighin prodimmediate exceptionusers seelost datavisibilityvisible - insertOne · insertone-duplicate-key-error-no-try-catcherrorWhenThe document violates a unique index constraint (E11000 error from MongoDB driver). This is NOT a ValidationError — it comes from the driver after the write attempt. insertOne() does not retry on duplicate key errors.Throws
MongoError with code: 11000Required handlingCaller MUST wrap in try-catch. Check error.code === 11000 to identify duplicate key violations. Use error.keyPattern to determine which field caused the conflict. This is the most common silent failure for user registration flows (duplicate email) and idempotent upsert patterns.costhighin prodimmediate exceptionusers seelost datavisibilityvisible - insertOne · insertone-discriminator-not-found-no-try-catcherrorWhenThe document has a discriminatorKey value that does not match any registered discriminator. insertOne() throws MongooseError with message "Discriminator X not found for model Y" before any DB write occurs.Throws
MongooseErrorRequired handlingCaller MUST wrap in try-catch. Check error.name === 'MongooseError'. Verify discriminator is registered via Model.discriminator() before inserting documents with dynamic discriminatorKey values.costmediumin prodimmediate exceptionusers seelost datavisibilityvisibleSources[32] - startSession · startsession-connection-not-ready-no-try-catcherrorWhenThe Mongoose connection is not open when startSession() is called. startSession() calls _waitForConnect() which rejects if the connection is in a failed or disconnected state.Throws
MongooseServerSelectionError or MongooseErrorRequired handlingCaller MUST wrap in try-catch. Ensure mongoose.connect() has resolved before calling startSession(). In serverless environments, check connection state with mongoose.connection.readyState === 1 before attempting to start a session.costhighin prodimmediate exceptionusers seelost datavisibilityvisible - startSession · startsession-session-not-ended-resource-leakwarningWhenstartSession() resolves successfully but the returned ClientSession is never ended (session.endSession() not called in a finally block). Sessions consume server resources and are subject to server-side timeout (default 30 minutes). In serverless or high-throughput environments, session leaks cause server connection pool exhaustion.Throws
Does not throw — silent resource leakRequired handlingALWAYS call session.endSession() in a finally block after using a session obtained via startSession(). Prefer connection.withSession() which handles session lifecycle automatically. Use connection.transaction() for transactional workflows — it manages session creation, commit, abort, and endSession.costhighin prodsilent failureusers seedegraded performancevisibilitysilent - withSession · withsession-executor-error-propagates-no-try-catcherrorWhenThe executor function throws an error or rejects. withSession() propagates the error to the caller after ending the session, but does NOT abort any in-flight transaction. If the executor started a transaction manually (session.startTransaction()), the caller must abort it before the error propagates or the transaction will be left dangling.Throws
Whatever the executor function throws — MongoError, MongooseError, or application errorRequired handlingCaller MUST wrap withSession() in try-catch. If the executor manually manages transactions (session.startTransaction()), use a try/finally inside the executor to call session.abortTransaction() on error rather than letting the error propagate with an open transaction. Prefer connection.transaction() which handles transaction abort automatically.costhighin prodimmediate exceptionusers seelost datavisibilityvisible - withSession · withsession-no-executor-throws-immediatelyerrorWhenwithSession() is called without an executor function argument. Throws MongooseError immediately: 'Please provide an executor function'.Throws
MongooseErrorRequired handlingAlways provide an executor function. This is a programmer error, not a runtime error — it should be caught during development.costlowin prodimmediate exceptionusers seelost datavisibilityvisibleSources[34] - init · init-index-build-error-no-try-catcherrorWhenIndex creation fails due to an incompatible existing index (different options on same field), insufficient privileges, or a connection error during the index build. init() rejects with a MongoError from the driver. In production environments, unique index creation on large collections is particularly prone to this.Throws
MongoError (from driver) or MongooseServerSelectionErrorRequired handlingIf explicitly awaiting Model.init(), wrap in try-catch. In production: NEVER rely on autoIndex for live databases — run index creation as a separate deployment step with ensureIndexes() or via the MongoDB shell. Set autoIndex: false in production and call Model.ensureIndexes() or Model.syncIndexes() explicitly. Index build failure does NOT prevent the model from being used — it only means the index may not exist.costmediumin prodimmediate exceptionusers seedegraded performancevisibilityvisible - init · init-connection-error-no-try-catcherrorWhenThe MongoDB connection is unavailable when init() attempts to create the collection or build indexes. init() calls _waitForConnect() internally but rejects if the server is unreachable.Throws
MongooseServerSelectionErrorRequired handlingWrap explicit Model.init() calls in try-catch. In application startup, use mongoose.connect().then(() => Model.init()) to ensure the connection is established first. Log init() failures at startup — silent init failures mean your indexes were never built and queries may be doing full collection scans.costhighin prodimmediate exceptionusers seedegraded performancevisibilitysilentSources[35] - syncIndexes · syncindexes-partial-failure-no-try-catcherrorWhenOne or more index operations (creation or deletion) fail during syncIndexes(). Mongoose throws a SyncIndexesError that contains an errors map detailing which indexes failed and why. The operation is NOT atomic — some indexes may have been dropped or created before the failure occurred.Throws
SyncIndexesError (extends MongooseError), with .errors property as a mapRequired handlingCaller MUST wrap in try-catch. Check error.name === 'SyncIndexesError' and inspect error.errors to determine which indexes failed. Since the operation is non-atomic, inspect the database state with Model.listIndexes() after a partial failure to understand what was applied. Roll back by re-running syncIndexes() or manually creating/dropping the failed index.costhighin prodimmediate exceptionusers seedegraded performancevisibilityvisibleSources[37] - syncIndexes · syncindexes-irreversible-drop-no-confirmationerrorWhensyncIndexes() drops indexes that are not in the current schema, including manually-created performance indexes not tracked by Mongoose. There is no confirmation prompt, dry-run mode is only available via diffIndexes(). Dropped indexes on large collections cause immediate query performance degradation.Throws
Does not throw — silent irreversible index dropRequired handlingALWAYS call Model.diffIndexes() first to preview what will be dropped and created. Review the toDrop array carefully — any custom performance index not in the schema will be permanently deleted. In CI/CD pipelines, fail the deployment if toDrop contains unexpected indexes. Never run syncIndexes() in hot-path application code.costhighin prodsilent failureusers seedegraded performancevisibilitysilentSources[37] - bulkWrite · connection-bulkwrite-mongoose-bulkwrite-error-no-try-catcherrorWhenConnection.bulkWrite() with `throwOnValidationError: true` (the default in Mongoose 8.x+) throws MongooseBulkWriteError when ANY op fails Mongoose schema validation (cast error, required field missing, validator returns false). Valid ops in the same batch still execute and persist — the error contains a `results` array of {success: true | error} per op and a `validationErrors` array of just the failures. Without try-catch the caller doesn't know which writes landed and which didn't.Throws
MongooseBulkWriteError (extends MongooseError) with .validationErrors, .results, .rawResult, .operationRequired handlingCaller MUST wrap in try-catch. Catch MongooseBulkWriteError and inspect err.validationErrors to enumerate which ops failed validation; inspect err.results to determine which ops succeeded on the server. Do NOT assume the entire bulkWrite was a no-op on failure — partial application is the normal case. To opt out of throwing, pass { throwOnValidationError: false } and inspect result.mongoose.validationErrors after the call.costhighin prodimmediate exceptionusers seelost transactionvisibilityvisible - bulkWrite · connection-bulkwrite-write-error-partial-applicationerrorWhenMongo-side write errors (E11000 duplicate key, document validation failure, server timeouts mid-batch) reject the returned Promise with the underlying mongodb driver's MongoBulkWriteError. Earlier ops in the batch may have already been applied. The error's .writeErrors array identifies which ops failed and .insertedCount / .modifiedCount / .deletedCount say how many succeeded before the batch aborted.Throws
MongoBulkWriteError (from mongodb driver) — propagates as Promise rejectionRequired handlingCaller MUST wrap in try-catch. Catch MongoBulkWriteError and reconcile state: read err.result for per-op success counts. The order ops execute in is implementation- defined when `ordered: false`; when `ordered: true` (default), all ops AFTER the first failure are skipped. Always log err.writeErrors before deciding whether to retry — duplicate key errors are not retryable but server-selection errors are.costhighin prodimmediate exceptionusers seelost transactionvisibilityvisible - destroy · connection-destroy-pending-writes-discardedwarningWhenConnection.destroy() force-closes the underlying MongoClient without waiting for pending operations to drain. Writes mid-flight that have been sent to the server but whose acknowledgement hasn't returned may or may not have been applied — the Promise resolves to void regardless. There is no API to enumerate which ops were aborted. Calling destroy() in a graceful-shutdown handler before draining writes loses commit acks.Throws
Resolves void on success; rejects only on internal MongoClient close errorsRequired handlingPREFER Connection.close() over destroy() in graceful shutdown handlers — close() waits for in-flight ops to complete. Use destroy() only when shutting down a process that is already failing (uncaughtException, SIGKILL pending) and you cannot afford to wait. If you must use destroy(), drain critical writes first (await Promise.all(pendingWrites)) before calling it. Wrap in try-catch defensively — internal close errors are rare but possible.costhighin prodsilent failureusers seelost transactionvisibilitysilentSources[41] - createCollections · createcollections-create-collections-error-no-try-catcherrorWhencreateCollections(true) aggregates per-collection failures into a CreateCollectionsError thrown after the batch completes. The .errors property is a Record mapping each failed collection name to its underlying error. Without try-catch, the partial-success state (which collections WERE created) is lost — the caller can't tell whether to retry only the failed names or assume all failed.Throws
CreateCollectionsError (extends MongooseError) with .errors mapRequired handlingCaller MUST wrap in try-catch. Catch CreateCollectionsError and inspect err.errors (Record<string, Error>) to enumerate which specific collections failed. Successfully- created collections are NOT rolled back — retry by passing only the failed names back into a follow-up createCollection() loop. If continueOnError is false (default), the first failure rejects immediately and the remaining collections in the batch are not attempted; partial creation still occurred for collections before the failure.costmediumin prodimmediate exceptionusers seedegraded performancevisibilityvisible - documentDeleteOne · document-deleteone-middleware-error-no-try-catcherrorWhenDocument.deleteOne() runs pre('deleteOne', { document: true, query: false }) middleware. Any pre-hook that throws or rejects (auth check failing, business rule blocking the delete) propagates out of the await. Without try-catch the caller assumes deletion succeeded — the document remains in the database while application state moves on as if it were gone.Throws
MongooseError or middleware-thrown error (any Error subclass thrown in pre('deleteOne') hook)Required handlingCaller MUST wrap in try-catch. After catching, treat the deletion as NOT having occurred — re-read the document by _id to confirm its state before retrying. Do not update dependent state (cache invalidation, downstream notifications) on the assumption that deleteOne succeeded.costhighin prodimmediate exceptionusers seelost datavisibilityvisible - documentDeleteOne · document-deleteone-zero-deletedcount-silent-noopwarningWhenDocument.deleteOne() resolves to a DeleteResult with deletedCount=0 when the document no longer exists in the database (race with another delete) or when a query-level filter eliminates it. The Promise does NOT reject — it resolves successfully with a "did nothing" result. Without inspecting deletedCount the caller believes the delete succeeded.Throws
Does not throw — silent zero-deletedCount on race or stale docRequired handlingALWAYS inspect result.deletedCount after await. If 0, treat the delete as a no-op and decide whether to surface a 404 to the caller, retry, or proceed (idempotent delete semantics). Do NOT assume deletedCount > 0 just because the await did not throw.costmediumin prodsilent failureusers seelost datavisibilitysilentSources[44] - createSearchIndexes · createsearchindexes-not-atlas-command-error-no-try-catcherrorWhencreateSearchIndexes() requires MongoDB Atlas (or Atlas Search Local). Running it against a self-hosted community-edition deployment rejects with a command-not-supported error (server reports $listSearchIndexes is not recognized). Without try-catch the deployment pipeline aborts silently on local-dev environments that don't have Atlas configured.Throws
MongoServerError (code 40324 or similar, 'Unrecognized pipeline stage name: $listSearchIndexes')Required handlingCaller MUST wrap in try-catch. Inspect err.codeName / err.code — if the cluster is non-Atlas, gracefully skip search index creation rather than crashing the startup sequence. In multi-environment deployments (Atlas in prod, community-edition in dev), conditionally call this only when process.env.MONGODB_ATLAS === 'true' to avoid the error entirely.costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible - createSearchIndexes · createsearchindexes-partial-creation-no-rollbackwarningWhencreateSearchIndexes() iterates the schema's searchIndexes array and creates them sequentially. If the 3rd of 5 indexes fails (invalid definition, duplicate name, quota), the first 2 are already created and remain in the cluster after the Promise rejects. There is no automatic rollback.Throws
MongoServerError on first-failed index — earlier indexes remainRequired handlingAfter catching, call Model.listSearchIndexes() to enumerate what WAS created and decide whether to drop the partial set and retry from scratch (atomic-like behavior) or accept the partial state. In CI/CD pipelines treat partial creation as a deployment failure and roll forward with explicit cleanup.costmediumin proddelayed failureusers seedegraded performancevisibilityvisibleSources[46] - eachAsync · eachasync-multi-error-no-try-catcherrorWheneachAsync(fn, { continueOnError: true }) collects errors thrown by fn() across all documents and rejects the final Promise with an EachAsyncMultiError whose .errors array contains all failures. Without try-catch the caller cannot enumerate which documents were processed successfully and which failed — partial-success state is silently dropped.Throws
EachAsyncMultiError (extends MongooseError) with .errors: Error[]Required handlingCaller MUST wrap in try-catch. Inspect err.errors to enumerate per-document failures. Each element retains the original error message; correlate by index if the iteration order is deterministic. Without continueOnError, the FIRST per-document error rejects immediately and remaining documents in the cursor are not visited — wrap that case as well.costmediumin prodimmediate exceptionusers seedegraded performancevisibilityvisible
Sources
Every postcondition cites at least one of these. Numbered to match the footnotes above.
- [1]mongoosejs.com/docs/connections.htmlhttps://mongoosejs.com/docs/connections.html
- [2]mongoosejs.com/docs/schematypes.htmlhttps://mongoosejs.com/docs/schematypes.html#what-is-a-schematype
- [3]mongoosejs.com/docs/schematypes.htmlhttps://mongoosejs.com/docs/schematypes.html
- [4]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#model_Model-findById
- [5]mongoosejs.com/docs/validation.htmlhttps://mongoosejs.com/docs/validation.html
- [6]mongoosejs.com/docs/validation.htmlhttps://mongoosejs.com/docs/validation.html#unique-indexes
- [7]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#model_Model-insertMany
- [8]security.snyk.io/vuln/SNYK-JS-MONGOOSE-5777721https://security.snyk.io/vuln/SNYK-JS-MONGOOSE-5777721
- [9]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#model_Model-findByIdAndUpdate
- [10]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#model_Model-findByIdAndDelete
- [11]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/document.html#document_Document-save
- [12]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/query.html#query_Query-exec
- [13]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/query.html#query_Query-orFail
- [14]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#model_Model-aggregate
- [15]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#model_Model-countDocuments
- [16]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#model_Model-updateMany
- [17]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#model_Model-replaceOne
- [18]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#model_Model-findOneAndReplace
- [19]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#model_Model-deleteMany
- [20]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#model_Model-findOneAndDelete
- [21]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#model_Model-estimatedDocumentCount
- [22]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#model_Model-exists
- [23]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#model_Model-distinct
- [24]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#model_Model-bulkWrite
- [25]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/document.html#document_Document-validate
- [26]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#Model.bulkSave()
- [27]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#Model.populate()
- [28]mongoosejs.com/docs/populate.htmlhttps://mongoosejs.com/docs/populate.html
- [29]mongoosejs.com/docs/transactions.htmlhttps://mongoosejs.com/docs/transactions.html
- [30]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/connection.html#Connection.prototype.transaction()
- [31]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/mongoose.html#Mongoose.prototype.disconnect()
- [32]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#Model.insertOne()
- [33]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/connection.html#Connection.prototype.startSession()
- [34]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/connection.html#Connection.prototype.withSession()
- [35]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#Model.init()
- [36]mongoosejs.com/docs/guide.htmlhttps://mongoosejs.com/docs/guide.html#autoIndex
- [37]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#Model.syncIndexes()
- [38]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/connection.html#Connection.prototype.bulkWrite()
- [39]github.com/Automattic/mongoosehttps://github.com/Automattic/mongoose/blob/master/lib/error/bulkWriteError.js
- [40]mongodb.com/docs/manualhttps://www.mongodb.com/docs/manual/reference/method/db.collection.bulkWrite/
- [41]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/connection.html#Connection.prototype.destroy()
- [42]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/connection.html#Connection.prototype.createCollections()
- [43]github.com/Automattic/mongoosehttps://github.com/Automattic/mongoose/blob/master/lib/error/createCollectionsError.js
- [44]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/document.html#Document.prototype.deleteOne()
- [45]mongoosejs.com/docs/middleware.htmlhttps://mongoosejs.com/docs/middleware.html#types-of-middleware
- [46]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#Model.createSearchIndexes()
- [47]mongodb.com/docs/atlashttps://www.mongodb.com/docs/atlas/atlas-search/manage-indexes/
- [48]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/query.html#Query.prototype.cursor()
- [49]github.com/Automattic/mongoosehttps://github.com/Automattic/mongoose/blob/master/lib/error/eachAsyncMultiError.js
Need a different package?
Request a profile