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

feat: useConnection(connection) function #14802

Open
wants to merge 4 commits into
base: 8.8
Choose a base branch
from
Open
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;
vkarpov15 marked this conversation as resolved.
Show resolved Hide resolved
};

/**
* 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();
vkarpov15 marked this conversation as resolved.
Show resolved Hide resolved
Model.useConnection(connection);
assert.equal(db.models[Model.modelName], undefined);
assert(connection.models[Model.modelName]);
});
});


Expand Down
Loading