Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

feat(connection): bubble up monitorCommands events to Mongoose connection if monitorCommands option set #14681

Merged
merged 1 commit into from
Jun 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
6 changes: 6 additions & 0 deletions lib/drivers/node-mongodb-native/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,12 @@ function _setClient(conn, client, options, dbName) {
});
}

if (options.monitorCommands) {
client.on('commandStarted', (data) => conn.emit('commandStarted', data));
client.on('commandFailed', (data) => conn.emit('commandFailed', data));
client.on('commandSucceeded', (data) => conn.emit('commandSucceeded', data));
}

conn.onOpen();

for (const i in conn.collections) {
Expand Down
24 changes: 23 additions & 1 deletion test/connection.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ describe('connections:', function() {
let conn;

before(async function() {
conn = mongoose.createConnection(start.uri2);
conn = mongoose.createConnection(start.uri2, { monitorCommands: true });
await conn.asPromise();
await conn.collection('test').deleteMany({});
return conn;
Expand Down Expand Up @@ -254,6 +254,28 @@ describe('connections:', function() {
assert.equal(events[1].method, 'findOne');
assert.deepStrictEqual(events[1].result, { _id: 17, answer: 42 });
});

it('commandStarted, commandFailed, commandSucceeded (gh-14611)', async function() {
let events = [];
conn.on('commandStarted', event => events.push(event));
conn.on('commandFailed', event => events.push(event));
conn.on('commandSucceeded', event => events.push(event));

await conn.collection('test').insertOne({ _id: 14611, answer: 42 });
assert.equal(events.length, 2);
assert.equal(events[0].constructor.name, 'CommandStartedEvent');
assert.equal(events[0].commandName, 'insert');
assert.equal(events[1].constructor.name, 'CommandSucceededEvent');
assert.equal(events[1].requestId, events[0].requestId);

events = [];
await conn.createCollection('tests', { capped: 1024 }).catch(() => {});
assert.equal(events.length, 2);
assert.equal(events[0].constructor.name, 'CommandStartedEvent');
assert.equal(events[0].commandName, 'create');
assert.equal(events[1].constructor.name, 'CommandFailedEvent');
assert.equal(events[1].requestId, events[0].requestId);
});
});

it('should allow closing a closed connection', async function() {
Expand Down
Loading