Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(connection): re-run Model.init() if re-connecting after explicitly closing a connection #12130

Merged
merged 1 commit into from Jul 26, 2022

Conversation

vkarpov15
Copy link
Collaborator

Fix #12047

Summary

The Model.init() function is responsible for:

  1. Calling createCollection() to ensure the Model's underlying collection exists, unless autoCreate = false
  2. Calling createIndexes() to ensure the indexes defined in the Model's schema exist, unless autoIndex = false

Mongoose calls Model.init() when you create a model using mongoose.model() or Collection.prototype.model(). The createCollection() and createIndexes() 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 runs init() when you call model(), and 2) Mongoose stores a $init property on a model that contains a promise wrapping the init() call here. If $init is set, then calling init() just returns $init. This is to avoid duplicate init() calls.

This fix deletes $init when the user calls Connection.prototype.close(), and ensures that Mongoose calls init() when the user opens a connection using openUri() or setClient(). So close() clears $init caches, and re-opening the connection means Mongoose re-runs init().

Related issue: #11916

Examples

See tests

Copy link
Collaborator

@AbdelrahmanHafez AbdelrahmanHafez left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, thanks 👍

@vkarpov15 vkarpov15 changed the base branch from master to 6.5 July 26, 2022 16:54
@vkarpov15 vkarpov15 merged commit 47c3231 into 6.5 Jul 26, 2022
@AbdelrahmanHafez AbdelrahmanHafez deleted the vkarpov15/gh-12047 branch July 26, 2022 17:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
3 participants