Skip to content

fix: validate connection instance in Model.useConnection() (#16098)#16103

Closed
22BRS1317 wants to merge 1 commit intoAutomattic:masterfrom
22BRS1317:fix/16098-useConnection-validation
Closed

fix: validate connection instance in Model.useConnection() (#16098)#16103
22BRS1317 wants to merge 1 commit intoAutomattic:masterfrom
22BRS1317:fix/16098-useConnection-validation

Conversation

@22BRS1317
Copy link
Copy Markdown

Problem

Model.useConnection() only validated that the connection argument was
not null or undefined, but accepted any non-nullish value (plain objects,
strings, numbers, etc.) without throwing an error. This led to confusing
failures later in the code rather than a clear error at the call site.

Solution

Added an instanceof Connection check immediately after the existing null
check in lib/model.js. If a non-Connection value is passed, a descriptive
MongooseError is thrown with the type and value of the invalid argument.

Changes

  • lib/model.js — added instanceof Connection validation in
    Model.useConnection() with a clear error message
  • test/model.test.js — added test case inside the existing
    describe('Model.useConnection()') block covering objects,
    strings, numbers, and null

Test

assert.throws(
  () => Model.useConnection({ not: 'a connection' }),
  /must be an instance of mongoose\.Connection/
);

Fixes #16098

@vkarpov15
Copy link
Copy Markdown
Collaborator

Closing in favor of #16149

@vkarpov15 vkarpov15 closed this Mar 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Model.useConnection() lacks validation for Connection instance, causing silent state corruption

2 participants