Skip to content

Commit

Permalink
feat(index): emit 'createConnection' event when user calls `mongoose.…
Browse files Browse the repository at this point in the history
…createConnection()`

Fix #9985
  • Loading branch information
vkarpov15 committed Mar 4, 2021
1 parent 5c5fcbc commit a57875b
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 0 deletions.
3 changes: 3 additions & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ if (global.MONGOOSE_DRIVER_PATH) {
}

const Document = require('./document');
const EventEmitter = require('events').EventEmitter;
const Schema = require('./schema');
const SchemaType = require('./schematype');
const SchemaTypes = require('./schema/index');
Expand Down Expand Up @@ -65,6 +66,7 @@ function Mongoose(options) {
this.connections = [];
this.models = {};
this.modelSchemas = {};
this.events = new EventEmitter();
// default global options
this.options = Object.assign({
pluralization: true
Expand Down Expand Up @@ -280,6 +282,7 @@ Mongoose.prototype.createConnection = function(uri, options, callback) {
options = null;
}
_mongoose.connections.push(conn);
_mongoose.events.emit('createConnection', conn);

if (arguments.length > 0) {
return conn.openUri(uri, options, callback);
Expand Down
6 changes: 6 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -530,8 +530,14 @@ describe('mongoose module:', function() {
cb();
});

const events = [];
mong.events.on('createConnection', conn => events.push(conn));

const db2 = mong.createConnection(process.env.MONGOOSE_TEST_URI || uri, options);

assert.equal(events.length, 1);
assert.equal(events[0], db2);

db2.on('open', function() {
connections++;
cb();
Expand Down

0 comments on commit a57875b

Please sign in to comment.