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(mongoose): make setDriver() update mongoose.model() connections and collections #14505

Merged
merged 3 commits into from Apr 7, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
22 changes: 22 additions & 0 deletions lib/model.js
Expand Up @@ -4893,6 +4893,28 @@ Model.compile = function compile(name, schema, collectionName, connection, base)
return model;
};

/*!
* ignore
*/
vkarpov15 marked this conversation as resolved.
Show resolved Hide resolved

Model.$__updateConnection = function $__updateConnection(newConnection) {
this.db = newConnection;
this.prototype.db = newConnection;
this.prototype[modelDbSymbol] = newConnection;

const collection = newConnection.collection(
this.collection.collectionName,
this.collection.opts
);

this.prototype.collection = collection;
this.prototype.$collection = collection;
this.prototype[modelCollectionSymbol] = collection;

this.collection = collection;
this.$__collection = collection;
};

/**
* Register custom query methods for this model
*
Expand Down
10 changes: 10 additions & 0 deletions lib/mongoose.js
Expand Up @@ -166,9 +166,19 @@ Mongoose.prototype.setDriver = function setDriver(driver) {
_mongoose.__driver = driver;

const Connection = driver.Connection;
const oldDefaultConnection = _mongoose.connections[0];
_mongoose.connections = [new Connection(_mongoose)];
_mongoose.connections[0].models = _mongoose.models;

// Update all models that pointed to the old default connection to
// the new default connection, including collections
for (const model of Object.values(_mongoose.models)) {
if (model.db !== oldDefaultConnection) {
continue;
}
model.$__updateConnection(_mongoose.connections[0]);
}

return _mongoose;
};

Expand Down