Intercpt command before sending it to server.

I am using the MongoDB native driver in Node.js and I want to intercept and modify the data before it is inserted into the database. Specifically, I want to intercept the insertOne command and modify the document being inserted.

I have tried using the commandStarted event to intercept the command, but modifying the document object inside the event listener does not affect the actual data being inserted into the database. although when I trow from here the insertion were not made which confirms that when this command is triggered it is yet to be send to server.

But still I am not able to modify document.

Here’s the code I have tried:

connection.on('commandStarted', event => {
  const operation = event.commandName as 'createIndexes' | 'find' | 'insert' | 'update';
  const collection = event?.command[operation];
  // if (operation === 'createIndexes') return;
  // log({ operation, collection });
  if (operation == 'insert') {
    const documents = event?.command?.documents as Record<string, any>[];
    if (!documents) throw new Error('Cannot insert without documents');
    for (const document of documents) {
      const validator = schemas[collection];
      if (validator) {
        const error = validator(_.omit(document, ['_id']))[0];
        // This works like when I throw the insertion is not made in db
        if (error) throw new Error(`Validation error: ${error}`);
      }
      // Here I want to modify the document before it is inserted
      // But This is not reflecting in db
      document.xyz = 'xyz';
    }
  }
});