Skip to content

Commit da15836

Browse files
authored
Merge pull request #14681 from Automattic/vkarpov15/gh-14611
feat(connection): bubble up monitorCommands events to Mongoose connection if `monitorCommands` option set
2 parents 9590792 + 094277f commit da15836

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

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

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -410,6 +410,12 @@ function _setClient(conn, client, options, dbName) {
410410
});
411411
}
412412

413+
if (options.monitorCommands) {
414+
client.on('commandStarted', (data) => conn.emit('commandStarted', data));
415+
client.on('commandFailed', (data) => conn.emit('commandFailed', data));
416+
client.on('commandSucceeded', (data) => conn.emit('commandSucceeded', data));
417+
}
418+
413419
conn.onOpen();
414420

415421
for (const i in conn.collections) {

test/connection.test.js

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -210,7 +210,7 @@ describe('connections:', function() {
210210
let conn;
211211

212212
before(async function() {
213-
conn = mongoose.createConnection(start.uri2);
213+
conn = mongoose.createConnection(start.uri2, { monitorCommands: true });
214214
await conn.asPromise();
215215
await conn.collection('test').deleteMany({});
216216
return conn;
@@ -254,6 +254,28 @@ describe('connections:', function() {
254254
assert.equal(events[1].method, 'findOne');
255255
assert.deepStrictEqual(events[1].result, { _id: 17, answer: 42 });
256256
});
257+
258+
it('commandStarted, commandFailed, commandSucceeded (gh-14611)', async function() {
259+
let events = [];
260+
conn.on('commandStarted', event => events.push(event));
261+
conn.on('commandFailed', event => events.push(event));
262+
conn.on('commandSucceeded', event => events.push(event));
263+
264+
await conn.collection('test').insertOne({ _id: 14611, answer: 42 });
265+
assert.equal(events.length, 2);
266+
assert.equal(events[0].constructor.name, 'CommandStartedEvent');
267+
assert.equal(events[0].commandName, 'insert');
268+
assert.equal(events[1].constructor.name, 'CommandSucceededEvent');
269+
assert.equal(events[1].requestId, events[0].requestId);
270+
271+
events = [];
272+
await conn.createCollection('tests', { capped: 1024 }).catch(() => {});
273+
assert.equal(events.length, 2);
274+
assert.equal(events[0].constructor.name, 'CommandStartedEvent');
275+
assert.equal(events[0].commandName, 'create');
276+
assert.equal(events[1].constructor.name, 'CommandFailedEvent');
277+
assert.equal(events[1].requestId, events[0].requestId);
278+
});
257279
});
258280

259281
it('should allow closing a closed connection', async function() {

0 commit comments

Comments
 (0)