Profiles·Public

mongoose

semver>=5.0.0postconditions69functions41last verified2026-06-23coverage score93%

Postconditions — what we check

  • find · connection-error-no-try-catch
    error
    WhenDatabase connection failed or was interrupted
    ThrowsMongooseError or MongoError
    Required 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 datavisibilityvisible
    Sources[1]
  • find · cast-error-no-try-catch
    error
    WhenQuery parameter cannot be cast to expected type
    ThrowsCastError
    Required 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 datavisibilityvisible
    Sources[2]
  • findOne · connection-error-no-try-catch
    error
    WhenDatabase connection failed
    ThrowsMongooseError or MongoError
    Required handlingCaller MUST wrap in try-catch or use .catch() to handle connection errors
    costhighin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[1]
  • findOne · cast-error-no-try-catch
    error
    WhenQuery parameter casting failed
    ThrowsCastError
    Required handlingCaller MUST wrap in try-catch to handle type casting errors
    costhighin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[3]
  • findById · cast-error-no-try-catch-invalid-id
    error
    WhenProvided ID is not a valid ObjectId format
    ThrowsCastError 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 datavisibilityvisible
    Sources[4]
  • findById · connection-error-no-try-catch
    error
    WhenDatabase connection failed
    ThrowsMongooseError
    Required handlingCaller MUST handle connection errors
    costhighin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[1]
  • create · validation-error-no-try-catch
    error
    WhenDocument validation failed (missing required fields, wrong types, custom validators)
    ThrowsValidationError with errors object containing field-specific ValidatorErrors
    Required 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 datavisibilityvisible
    Sources[5]
  • create · duplicate-key-error-no-try-catch
    error
    WhenUnique constraint violation (E11000 error)
    ThrowsMongoError with code: 11000
    Required 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 datavisibilityvisible
    Sources[6]
  • create · connection-error-no-try-catch
    error
    WhenDatabase connection failed
    ThrowsMongooseError
    Required handlingCaller MUST handle connection errors with retry logic
    costhighin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[1]
  • insertMany · validation-error-no-try-catch
    error
    WhenOne or more documents fail validation
    ThrowsValidationError
    Required handlingCaller MUST wrap in try-catch. Default behavior stops on first error; use ordered:false to continue on errors.
    costhighin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[7]
  • insertMany · duplicate-key-error-no-try-catch
    error
    WhenDuplicate key constraint violation
    ThrowsMongoError with code: 11000
    Required handlingCaller MUST wrap in try-catch and handle duplicate key errors
    costhighin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[7]
  • updateOne · validation-error-no-try-catch
    error
    WhenUpdate violates validation rules
    ThrowsValidationError
    Required handlingCaller MUST wrap in try-catch to handle validation errors
    costhighin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[5]
  • updateOne · cast-error-no-try-catch
    error
    WhenUpdate value cannot be cast to schema type
    ThrowsCastError
    Required handlingCaller MUST wrap in try-catch to handle type errors
    costhighin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[3]
  • updateOne · connection-error-no-try-catch
    error
    WhenDatabase connection failed
    ThrowsMongooseError
    Required handlingCaller MUST handle connection errors
    costhighin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[1]
  • findByIdAndUpdate · prototype-pollution-cve-2023-3696-no-try-catch
    error
    WhenMalicious update payload exploits prototype pollution vulnerability
    ThrowsMay not throw - vulnerability allows arbitrary code execution
    Required 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 datavisibilityvisible
    Sources[8]
  • findByIdAndUpdate · validation-error-no-try-catch
    error
    WhenUpdate violates validation rules
    ThrowsValidationError
    Required handlingCaller MUST wrap in try-catch
    costhighin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[5]
  • findByIdAndUpdate · cast-error-no-try-catch
    error
    WhenInvalid ObjectId or type casting failure
    ThrowsCastError
    Required handlingCaller MUST wrap in try-catch
    costhighin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[9]
  • findOneAndUpdate · prototype-pollution-cve-2023-3696-no-try-catch
    error
    WhenVulnerable to prototype pollution attacks
    ThrowsMay not throw - allows RCE
    Required handlingCaller MUST wrap in try-catch and validate input. Upgrade mongoose to patched version.
    costhighin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[8]
  • findOneAndUpdate · validation-error-no-try-catch
    error
    WhenUpdate violates validation
    ThrowsValidationError
    Required handlingCaller MUST wrap in try-catch
    costhighin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[5]
  • deleteOne · connection-error-no-try-catch
    error
    WhenDatabase connection failed
    ThrowsMongooseError
    Required handlingCaller MUST wrap in try-catch
    costhighin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[1]
  • findByIdAndDelete · cast-error-no-try-catch
    error
    WhenInvalid ObjectId format
    ThrowsCastError
    Required handlingCaller MUST wrap in try-catch
    costhighin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[10]
  • findByIdAndDelete · connection-error-no-try-catch
    error
    WhenDatabase connection failed
    ThrowsMongooseError
    Required handlingCaller MUST wrap in try-catch
    costhighin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[1]
  • save · validation-error-no-try-catch
    error
    WhenDocument validation failed
    ThrowsValidationError with errors object
    Required handlingCaller MUST wrap in try-catch. Most common error when saving documents. Inspect error.errors for field-specific validation failures.
    costhighin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[11]
  • save · duplicate-key-error-no-try-catch
    error
    WhenUnique constraint violation
    ThrowsMongoError with code: 11000
    Required 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 datavisibilityvisible
    Sources[6]
  • save · connection-error-no-try-catch
    error
    WhenDatabase connection failed
    ThrowsMongooseError
    Required handlingCaller MUST wrap in try-catch
    costhighin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[1]
  • exec · query-error-no-try-catch
    error
    WhenQuery execution failed
    ThrowsMongooseError, CastError, or ValidationError depending on failure type
    Required 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 datavisibilityvisible
    Sources[12]
  • orFail · document-not-found-no-try-catch
    error
    WhenNo documents match the query
    ThrowsDocumentNotFoundError
    Required 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 datavisibilityvisible
    Sources[13]
  • connect · connection-failed-no-try-catch
    error
    WhenCannot connect to MongoDB (network, auth, or invalid connection string)
    ThrowsMongooseError or MongoError
    Required handlingCaller MUST wrap in try-catch. Connection failures should stop application startup. Log error details and exit gracefully.
    costhighin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[1]
  • aggregate · aggregation-error-no-try-catch
    error
    WhenInvalid pipeline stage or aggregation failure
    ThrowsMongooseError or MongoError
    Required handlingCaller MUST wrap in try-catch. Aggregation pipelines can fail with complex stage errors.
    costhighin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[14]
  • countDocuments · connection-error-no-try-catch
    error
    WhenDatabase connection failed
    ThrowsMongooseError
    Required handlingCaller MUST wrap in try-catch
    costhighin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[15]
  • updateMany · connection-error-no-try-catch
    error
    WhenDatabase connection failed
    ThrowsMongooseError
    Required handlingCaller MUST wrap in try-catch
    costhighin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[16]
  • replaceOne · connection-error-no-try-catch
    error
    WhenDatabase connection failed
    ThrowsMongooseError
    Required handlingCaller MUST wrap in try-catch
    costhighin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[17]
  • findOneAndReplace · connection-error-no-try-catch
    error
    WhenDatabase connection failed
    ThrowsMongooseError
    Required handlingCaller MUST wrap in try-catch
    costhighin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[18]
  • deleteMany · connection-error-no-try-catch
    error
    WhenDatabase connection failed
    ThrowsMongooseError
    Required handlingCaller MUST wrap in try-catch
    costhighin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[19]
  • findOneAndDelete · connection-error-no-try-catch
    error
    WhenDatabase connection failed
    ThrowsMongooseError
    Required handlingCaller MUST wrap in try-catch
    costhighin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[20]
  • estimatedDocumentCount · connection-error-no-try-catch
    error
    WhenDatabase connection failed
    ThrowsMongooseError
    Required handlingCaller MUST wrap in try-catch
    costhighin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[21]
  • exists · connection-error-no-try-catch
    error
    WhenDatabase connection failed
    ThrowsMongooseError
    Required handlingCaller MUST wrap in try-catch
    costhighin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[22]
  • distinct · connection-error-no-try-catch
    error
    WhenDatabase connection failed
    ThrowsMongooseError
    Required handlingCaller MUST wrap in try-catch
    costhighin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[23]
  • bulkWrite · connection-error-no-try-catch
    error
    WhenDatabase connection failed or bulk operation error
    ThrowsMongooseError or BulkWriteError
    Required handlingCaller MUST wrap in try-catch
    costhighin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[24]
  • validate · validation-error-no-try-catch
    error
    WhenDocument fails schema validation
    ThrowsValidationError
    Required handlingCaller MUST wrap in try-catch. ValidationError contains field-specific errors.
    costhighin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[25]
  • bulkSave · bulksave-validation-error-no-try-catch
    error
    WhenAny 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.
    ThrowsValidationError 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 datavisibilityvisible
    Sources[26]
  • bulkSave · bulksave-document-not-found-no-try-catch
    error
    WhenbulkWrite() 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.
    ThrowsMongooseBulkSaveIncompleteError (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 datavisibilitysilent
    Sources[26]
  • bulkSave · bulksave-duplicate-key-error-no-try-catch
    error
    WhenbulkWrite() fails due to a unique constraint violation (MongoDB E11000 duplicate key error) or a connection/network failure. The entire bulkWrite() round trip fails.
    ThrowsMongoError with code: 11000 for duplicate key, or MongooseError for connection failure
    Required 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 datavisibilityvisible
    Sources[26]
  • populate · populate-strict-populate-error-no-try-catch
    error
    WhenAttempting 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.
    ThrowsStrictPopulateError (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
    Sources[27][28]
  • populate · populate-cast-error-no-try-catch
    error
    WhenThe 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.
    ThrowsCastError (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 datavisibilityvisible
    Sources[27]
  • populate · populate-connection-error-no-try-catch
    error
    WhenDatabase connection fails while fetching referenced documents. populate() issues additional queries to the database for each populated path — each query can fail independently.
    ThrowsMongooseError or MongoError
    Required 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 datavisibilityvisible
    Sources[28]
  • transaction · transaction-abort-error-no-try-catch
    error
    WhenThe 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.
    ThrowsMongoError or any error thrown by the transaction function
    Required 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
    Sources[29][30]
  • transaction · transaction-parallel-operations-undefined-behavior
    error
    WhenUsing 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."
    ThrowsUndefined — may succeed, may corrupt data, may throw intermittently
    Required 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 datavisibilitysilent
    Sources[29]
  • disconnect · disconnect-error-no-try-catch
    warning
    WhenOne 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.
    ThrowsMongooseError or MongoError
    Required 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 unavailablevisibilitysilent
    Sources[31]
  • insertOne · insertone-validation-error-no-try-catch
    error
    WhenThe document fails schema validation (required field missing, type mismatch, custom validator rejection). insertOne() calls $save() internally which runs the full validation pipeline.
    ThrowsValidationError
    Required 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
    Sources[32][5]
  • insertOne · insertone-duplicate-key-error-no-try-catch
    error
    WhenThe 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.
    ThrowsMongoError with code: 11000
    Required 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
    Sources[32][6]
  • insertOne · insertone-discriminator-not-found-no-try-catch
    error
    WhenThe 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.
    ThrowsMongooseError
    Required 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 datavisibilityvisible
    Sources[32]
  • startSession · startsession-connection-not-ready-no-try-catch
    error
    WhenThe Mongoose connection is not open when startSession() is called. startSession() calls _waitForConnect() which rejects if the connection is in a failed or disconnected state.
    ThrowsMongooseServerSelectionError or MongooseError
    Required 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
    Sources[33][1]
  • startSession · startsession-session-not-ended-resource-leak
    warning
    WhenstartSession() 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.
    ThrowsDoes not throw — silent resource leak
    Required 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
    Sources[33][29]
  • withSession · withsession-executor-error-propagates-no-try-catch
    error
    WhenThe 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.
    ThrowsWhatever the executor function throws — MongoError, MongooseError, or application error
    Required 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
    Sources[34][29]
  • withSession · withsession-no-executor-throws-immediately
    error
    WhenwithSession() is called without an executor function argument. Throws MongooseError immediately: 'Please provide an executor function'.
    ThrowsMongooseError
    Required handlingAlways provide an executor function. This is a programmer error, not a runtime error — it should be caught during development.
    costlowin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[34]
  • init · init-index-build-error-no-try-catch
    error
    WhenIndex 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.
    ThrowsMongoError (from driver) or MongooseServerSelectionError
    Required 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
    Sources[35][36]
  • init · init-connection-error-no-try-catch
    error
    WhenThe 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.
    ThrowsMongooseServerSelectionError
    Required 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 performancevisibilitysilent
    Sources[35]
  • syncIndexes · syncindexes-partial-failure-no-try-catch
    error
    WhenOne 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.
    ThrowsSyncIndexesError (extends MongooseError), with .errors property as a map
    Required 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 performancevisibilityvisible
    Sources[37]
  • syncIndexes · syncindexes-irreversible-drop-no-confirmation
    error
    WhensyncIndexes() 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.
    ThrowsDoes not throw — silent irreversible index drop
    Required 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 performancevisibilitysilent
    Sources[37]
  • bulkWrite · connection-bulkwrite-mongoose-bulkwrite-error-no-try-catch
    error
    WhenConnection.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.
    ThrowsMongooseBulkWriteError (extends MongooseError) with .validationErrors, .results, .rawResult, .operation
    Required 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
    Sources[38][39]
  • bulkWrite · connection-bulkwrite-write-error-partial-application
    error
    WhenMongo-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.
    ThrowsMongoBulkWriteError (from mongodb driver) — propagates as Promise rejection
    Required 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
    Sources[40][38]
  • destroy · connection-destroy-pending-writes-discarded
    warning
    WhenConnection.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.
    ThrowsResolves void on success; rejects only on internal MongoClient close errors
    Required 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 transactionvisibilitysilent
    Sources[41]
  • createCollections · createcollections-create-collections-error-no-try-catch
    error
    WhencreateCollections(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.
    ThrowsCreateCollectionsError (extends MongooseError) with .errors map
    Required 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
    Sources[42][43]
  • documentDeleteOne · document-deleteone-middleware-error-no-try-catch
    error
    WhenDocument.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.
    ThrowsMongooseError 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
    Sources[44][45]
  • documentDeleteOne · document-deleteone-zero-deletedcount-silent-noop
    warning
    WhenDocument.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.
    ThrowsDoes not throw — silent zero-deletedCount on race or stale doc
    Required 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 datavisibilitysilent
    Sources[44]
  • createSearchIndexes · createsearchindexes-not-atlas-command-error-no-try-catch
    error
    WhencreateSearchIndexes() 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.
    ThrowsMongoServerError (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
    Sources[46][47]
  • createSearchIndexes · createsearchindexes-partial-creation-no-rollback
    warning
    WhencreateSearchIndexes() 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.
    ThrowsMongoServerError on first-failed index — earlier indexes remain
    Required 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 performancevisibilityvisible
    Sources[46]
  • eachAsync · eachasync-multi-error-no-try-catch
    error
    WheneachAsync(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.
    ThrowsEachAsyncMultiError (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[48][49]

Sources

Every postcondition cites at least one of these. Numbered to match the footnotes above.

  1. [1]mongoosejs.com/docs/connections.htmlhttps://mongoosejs.com/docs/connections.html
  2. [2]mongoosejs.com/docs/schematypes.htmlhttps://mongoosejs.com/docs/schematypes.html#what-is-a-schematype
  3. [3]mongoosejs.com/docs/schematypes.htmlhttps://mongoosejs.com/docs/schematypes.html
  4. [4]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#model_Model-findById
  5. [5]mongoosejs.com/docs/validation.htmlhttps://mongoosejs.com/docs/validation.html
  6. [6]mongoosejs.com/docs/validation.htmlhttps://mongoosejs.com/docs/validation.html#unique-indexes
  7. [7]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#model_Model-insertMany
  8. [8]security.snyk.io/vuln/SNYK-JS-MONGOOSE-5777721https://security.snyk.io/vuln/SNYK-JS-MONGOOSE-5777721
  9. [9]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#model_Model-findByIdAndUpdate
  10. [10]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#model_Model-findByIdAndDelete
  11. [11]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/document.html#document_Document-save
  12. [12]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/query.html#query_Query-exec
  13. [13]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/query.html#query_Query-orFail
  14. [14]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#model_Model-aggregate
  15. [15]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#model_Model-countDocuments
  16. [16]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#model_Model-updateMany
  17. [17]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#model_Model-replaceOne
  18. [18]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#model_Model-findOneAndReplace
  19. [19]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#model_Model-deleteMany
  20. [20]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#model_Model-findOneAndDelete
  21. [21]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#model_Model-estimatedDocumentCount
  22. [22]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#model_Model-exists
  23. [23]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#model_Model-distinct
  24. [24]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#model_Model-bulkWrite
  25. [25]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/document.html#document_Document-validate
  26. [26]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#Model.bulkSave()
  27. [27]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#Model.populate()
  28. [28]mongoosejs.com/docs/populate.htmlhttps://mongoosejs.com/docs/populate.html
  29. [29]mongoosejs.com/docs/transactions.htmlhttps://mongoosejs.com/docs/transactions.html
  30. [30]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/connection.html#Connection.prototype.transaction()
  31. [31]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/mongoose.html#Mongoose.prototype.disconnect()
  32. [32]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#Model.insertOne()
  33. [33]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/connection.html#Connection.prototype.startSession()
  34. [34]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/connection.html#Connection.prototype.withSession()
  35. [35]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#Model.init()
  36. [36]mongoosejs.com/docs/guide.htmlhttps://mongoosejs.com/docs/guide.html#autoIndex
  37. [37]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#Model.syncIndexes()
  38. [38]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/connection.html#Connection.prototype.bulkWrite()
  39. [39]github.com/Automattic/mongoosehttps://github.com/Automattic/mongoose/blob/master/lib/error/bulkWriteError.js
  40. [40]mongodb.com/docs/manualhttps://www.mongodb.com/docs/manual/reference/method/db.collection.bulkWrite/
  41. [41]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/connection.html#Connection.prototype.destroy()
  42. [42]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/connection.html#Connection.prototype.createCollections()
  43. [43]github.com/Automattic/mongoosehttps://github.com/Automattic/mongoose/blob/master/lib/error/createCollectionsError.js
  44. [44]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/document.html#Document.prototype.deleteOne()
  45. [45]mongoosejs.com/docs/middleware.htmlhttps://mongoosejs.com/docs/middleware.html#types-of-middleware
  46. [46]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/model.html#Model.createSearchIndexes()
  47. [47]mongodb.com/docs/atlashttps://www.mongodb.com/docs/atlas/atlas-search/manage-indexes/
  48. [48]mongoosejs.com/docs/apihttps://mongoosejs.com/docs/api/query.html#Query.prototype.cursor()
  49. [49]github.com/Automattic/mongoosehttps://github.com/Automattic/mongoose/blob/master/lib/error/eachAsyncMultiError.js
Need a different package?
Request a profile