Skip to content

Commit

Permalink
Merge pull request #14505 from Automattic/vkarpov15/set-driver-model-…
Browse files Browse the repository at this point in the history
…db-2

fix(mongoose): make setDriver() update mongoose.model() connections and collections
  • Loading branch information
vkarpov15 committed Apr 7, 2024
2 parents d475ce8 + 9fb1d81 commit 7cf76cc
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
28 changes: 28 additions & 0 deletions lib/model.js
Expand Up @@ -4895,6 +4895,34 @@ Model.compile = function compile(name, schema, collectionName, connection, base)
return model;
};

/**
* Update this model to use the new connection, including updating all internal
* references and creating a new `COllection` instance using the new connection.
* Not for external use, only used by `setDriver()` to ensure that you can still
* call `setDriver()` after creating a model using `mongoose.model()`.
*
* @param {Connection} newConnection the new connection to use
* @api private
*/

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

0 comments on commit 7cf76cc

Please sign in to comment.