Skip to content

Commit 7cf76cc

Browse files
authoredApr 7, 2024
Merge pull request #14505 from Automattic/vkarpov15/set-driver-model-db-2
fix(mongoose): make setDriver() update mongoose.model() connections and collections
2 parents d475ce8 + 9fb1d81 commit 7cf76cc

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed
 

‎lib/model.js

+28
Original file line numberDiff line numberDiff line change
@@ -4895,6 +4895,34 @@ Model.compile = function compile(name, schema, collectionName, connection, base)
48954895
return model;
48964896
};
48974897

4898+
/**
4899+
* Update this model to use the new connection, including updating all internal
4900+
* references and creating a new `COllection` instance using the new connection.
4901+
* Not for external use, only used by `setDriver()` to ensure that you can still
4902+
* call `setDriver()` after creating a model using `mongoose.model()`.
4903+
*
4904+
* @param {Connection} newConnection the new connection to use
4905+
* @api private
4906+
*/
4907+
4908+
Model.$__updateConnection = function $__updateConnection(newConnection) {
4909+
this.db = newConnection;
4910+
this.prototype.db = newConnection;
4911+
this.prototype[modelDbSymbol] = newConnection;
4912+
4913+
const collection = newConnection.collection(
4914+
this.collection.collectionName,
4915+
this.collection.opts
4916+
);
4917+
4918+
this.prototype.collection = collection;
4919+
this.prototype.$collection = collection;
4920+
this.prototype[modelCollectionSymbol] = collection;
4921+
4922+
this.collection = collection;
4923+
this.$__collection = collection;
4924+
};
4925+
48984926
/**
48994927
* Register custom query methods for this model
49004928
*

‎lib/mongoose.js

+10
Original file line numberDiff line numberDiff line change
@@ -166,9 +166,19 @@ Mongoose.prototype.setDriver = function setDriver(driver) {
166166
_mongoose.__driver = driver;
167167

168168
const Connection = driver.Connection;
169+
const oldDefaultConnection = _mongoose.connections[0];
169170
_mongoose.connections = [new Connection(_mongoose)];
170171
_mongoose.connections[0].models = _mongoose.models;
171172

173+
// Update all models that pointed to the old default connection to
174+
// the new default connection, including collections
175+
for (const model of Object.values(_mongoose.models)) {
176+
if (model.db !== oldDefaultConnection) {
177+
continue;
178+
}
179+
model.$__updateConnection(_mongoose.connections[0]);
180+
}
181+
172182
return _mongoose;
173183
};
174184

0 commit comments

Comments
 (0)