fix(connection): re-run Model.init()
if re-connecting after explicitly closing a connection
#12130
+85
−2
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fix #12047
Summary
The
Model.init()
function is responsible for:createCollection()
to ensure the Model's underlying collection exists, unlessautoCreate = false
createIndexes()
to ensure the indexes defined in the Model's schema exist, unlessautoIndex = false
Mongoose calls
Model.init()
when you create a model usingmongoose.model()
orCollection.prototype.model()
. ThecreateCollection()
andcreateIndexes()
calls are queued up until Mongoose connects to MongoDB.The issue is that, if you close a connection and then reconnect to a different database or cluster, Mongoose won't re-run
init()
. Because 1) Mongoose only runsinit()
when you callmodel()
, and 2) Mongoose stores a$init
property on a model that contains a promise wrapping theinit()
call here. If$init
is set, then callinginit()
just returns$init
. This is to avoid duplicateinit()
calls.This fix deletes
$init
when the user callsConnection.prototype.close()
, and ensures that Mongoose callsinit()
when the user opens a connection usingopenUri()
orsetClient()
. Soclose()
clears$init
caches, and re-opening the connection means Mongoose re-runsinit()
.Related issue: #11916
Examples
See tests