Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,21 @@ Model.prototype.$isMongooseModelPrototype = true;

Model.prototype.db;

/**
* @api public
*/

Model.useConnection = function useConnection(connection) {
if (!connection) {
throw new Error('Please provide a connection.');
}
if (this.db) {
delete this.db.models[this.modelName];
}
this.db = connection;
connection.models[this.modelName] = this;
};

/**
* The collection instance this model uses.
* A Mongoose collection is a thin wrapper around a [MongoDB Node.js driver collection]([MongoDB Node.js driver collection](https://mongodb.github.io/node-mongodb-native/Next/classes/Collection.html)).
Expand Down
10 changes: 10 additions & 0 deletions test/model.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -7575,6 +7575,16 @@ describe('Model', function() {

assert.strictEqual(doc.__v, 0);
});
it('updates the model\'s db property to point to the provided connection instance and vice versa', async function() {
const schema = new mongoose.Schema({
name: String
});
const Model = db.model('Test', schema);
const connection = start();
Model.useConnection(connection);
assert.equal(db.models[Model.modelName], undefined);
assert(connection.models[Model.modelName]);
});
});


Expand Down