Skip to content

Commit

Permalink
Merge pull request #12990 from lpizzinidev/gh-12966
Browse files Browse the repository at this point in the history
fix(connection): handles unique autoincrement ID for connections
  • Loading branch information
vkarpov15 authored Feb 3, 2023
2 parents 7c6fbb2 + 9e10a5e commit 748cb51
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ function Connection(base) {
if (typeof base === 'undefined' || !base.connections.length) {
this.id = 0;
} else {
this.id = base.connections.length;
this.id = base.nextConnectionId;
}
this._queue = [];
}
Expand Down
23 changes: 23 additions & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ const objectIdHexRegexp = /^[0-9A-Fa-f]{24}$/;
*/
function Mongoose(options) {
this.connections = [];
this.nextConnectionId = 0;
this.models = {};
this.events = new EventEmitter();
this.__driver = driver.get();
Expand Down Expand Up @@ -345,6 +346,7 @@ Mongoose.prototype.createConnection = function(uri, options, callback) {
options = null;
}
_mongoose.connections.push(conn);
_mongoose.nextConnectionId++;
_mongoose.events.emit('createConnection', conn);

if (arguments.length > 0) {
Expand Down Expand Up @@ -789,6 +791,27 @@ Mongoose.prototype.__defineSetter__('connection', function(v) {

Mongoose.prototype.connections;

/**
* An integer containing the value of the next connection id. Calling
* [`createConnection()`](#mongoose_Mongoose-createConnection) increments
* this value.
*
* #### Example:
*
* const mongoose = require('mongoose');
* mongoose.createConnection(); // id `0`, `nextConnectionId` becomes `1`
* mongoose.createConnection(); // id `1`, `nextConnectionId` becomes `2`
* mongoose.connections[0].destroy() // Removes connection with id `0`
* mongoose.createConnection(); // id `2`, `nextConnectionId` becomes `3`
*
* @memberOf Mongoose
* @instance
* @property {Number} nextConnectionId
* @api private
*/

Mongoose.prototype.nextConnectionId;

/**
* The Mongoose Aggregate constructor
*
Expand Down
12 changes: 12 additions & 0 deletions test/connection.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1514,4 +1514,16 @@ describe('connections:', function() {

await m.disconnect();
});

it('should create connections with unique IDs also if one has been destroyed (gh-12966)', function() {
const m = new mongoose.Mongoose();
m.createConnection();
m.createConnection();
m.connections[0].destroy();
m.createConnection();
m.createConnection();
m.createConnection();
const connectionIds = m.connections.map(c => c.id);
assert.deepEqual(connectionIds, [1, 2, 3, 4, 5]);
});
});

0 comments on commit 748cb51

Please sign in to comment.