Skip to content

Commit c40ccdf

Browse files
committed
fix(connection): propagate changes to _lastHeartbeatAt to useDb() child connections
Fix #15635
1 parent 907bd68 commit c40ccdf

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

lib/drivers/node-mongodb-native/connection.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ NativeConnection.prototype.useDb = function(name, options) {
118118

119119
newConn.name = name;
120120

121-
// push onto the otherDbs stack, this is used when state changes
121+
// push onto the otherDbs stack, this is used when state changes and when heartbeat is received
122122
if (options.noListener !== true) {
123123
this.otherDbs.push(newConn);
124124
}
@@ -501,6 +501,9 @@ function _setClient(conn, client, options, dbName) {
501501

502502
client.on('serverHeartbeatSucceeded', () => {
503503
conn._lastHeartbeatAt = Date.now();
504+
for (const otherDb of conn.otherDbs) {
505+
otherDb._lastHeartbeatAt = conn._lastHeartbeatAt;
506+
}
504507
});
505508

506509
if (options.monitorCommands) {

test/connection.test.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -870,6 +870,22 @@ describe('connections:', function() {
870870

871871
await db.close();
872872
});
873+
874+
it('updates child dbs lastHeartbeatAt (gh-15635)', async function () {
875+
const db = await mongoose.createConnection(start.uri).asPromise();
876+
877+
const schema = mongoose.Schema({ name: String }, { autoCreate: false, autoIndex: false });
878+
const Test = db.model('Test', schema);
879+
await Test.deleteMany({});
880+
await Test.create({ name: 'gh-11821' });
881+
882+
const db2 = db.useDb(start.databases[1]);
883+
884+
const now = Date.now();
885+
db.client.emit('serverHeartbeatSucceeded');
886+
assert.ok(db._lastHeartbeatAt >= now);
887+
assert.ok(db2._lastHeartbeatAt >= now);
888+
});
873889
});
874890

875891
describe('shouldAuthenticate()', function() {

0 commit comments

Comments
 (0)