Skip to content

Duplicate afterLoad Event Triggered in MongoDB Driver when Using findOne #11091

Closed

Description

@morrow-lw-dog

Issue description

I'm experiencing an issue with TypeORM when using the MongoDB driver in combination with an EntitySubscriber. Specifically, when executing a findOne operation, the afterLoad event is being triggered twice, even though the findOne method is only called once.

Expected Behavior

The afterLoad event should be triggered only once per entity load operation.

Actual Behavior

The afterLoad event is triggered twice for a single findOne operation.

Steps to reproduce

  1. Create an EntitySubscriber that listens for the afterLoad event.

    import { EntitySubscriberInterface, EventSubscriber, LoadEvent } from 'typeorm';
    
    @EventSubscriber()
    export class MyEntitySubscriber implements EntitySubscriberInterface {
      listenTo() {
        return YourEntity;
      }
    
      afterLoad(entity: YourEntity, event?: LoadEvent<YourEntity>): void {
        console.log('afterLoad triggered for entity:', entity);
      }
    }
  2. Perform a findOne operation on an entity using the MongoDB driver.

    const entity = await this.mongoRepository.findOne({ where: { _id: someObjectId } });
  3. Observe the output: The afterLoad event is logged twice, indicating it's been triggered twice for a single findOne call.

My Environment

Dependency Version
Operating System MacOS
Node.js version 18.19.0
Typescript version 5.2.2
TypeORM version 0.3.20

Additional Context

This issue seems specific to the MongoDB driver due to the way it handles cursors and async iteration. It does not appear to affect other database drivers.

Investigation Details:

Upon investigating, I found that in the MongoEntityManager.ts file, the applyEntityTransformationToCursor method overrides both the toArray and next methods of the cursor to apply entity transformations and broadcast the Load event.

Here's the relevant code snippet:

protected applyEntityTransformationToCursor<Entity extends ObjectLiteral>(
    metadata: EntityMetadata,
    cursor: FindCursor<Entity> | AggregationCursor<Entity>,
) {
    const queryRunner = this.mongoQueryRunner;

    // Save original toArray method
    (cursor as any)["__to_array_func"] = cursor.toArray;

    // Override toArray method
    cursor.toArray = async () =>
        ((cursor as any)["__to_array_func"] as CallableFunction)().then(
            async (results: Entity[]) => {
                const transformer = new DocumentToEntityTransformer();
                const entities = transformer.transformAll(results, metadata);
                // Broadcast "Load" event
                await queryRunner.broadcaster.broadcast(
                    "Load",
                    metadata,
                    entities,
                );
                return entities;
            },
        );

    // Save original next method
    (cursor as any)["__next_func"] = cursor.next;

    // Override next method
    cursor.next = async () =>
        ((cursor as any)["__next_func"] as CallableFunction)().then(
            async (result: Entity) => {
                if (!result) {
                    return result;
                }
                const transformer = new DocumentToEntityTransformer();
                const entity = transformer.transform(result, metadata);
                // Broadcast "Load" event
                await queryRunner.broadcaster.broadcast("Load", metadata, [
                    entity,
                ]);
                return entity;
            },
        );
}

The MongoDB driver's toArray method internally uses an async iterator that calls the overridden next method, as shown in the driver's code(src/cursor/abstract_cursor.ts):

async *[Symbol.asyncIterator](): AsyncGenerator<TSchema, void, void> {
    if (this.closed) {
      return;
    }

    try {
      while (true) {
        // Look Here 👇
        const document = await this.next();
        // ...
    } finally {
     // ...
  }

async toArray(): Promise<TSchema[]> {
  const array = [];
  for await (const document of this) {
    array.push(document);
  }
  return array;
}

This means that when toArray is called, it internally calls next for each document. Since both toArray and next have been overridden to broadcast the Load event, the event is triggered twice for each document when toArray is used.

In the case of findOne, which ultimately calls toArray with a limit of 1, the afterLoad event is triggered twice.

Possible Solution:

To resolve this issue, consider modifying the applyEntityTransformationToCursor method to prevent double-triggering of the Load event. One possible solution is to only broadcast the Load event within the next method and avoid doing so in the toArray method, since toArray relies on next.

Alternatively, implement a check to prevent the Load event from being broadcasted twice for the same entity when toArray internally calls next.

export class MongoEntityManager extends EntityManager {
    // prevent duplicate transformation
    readonly "@transformedFlag" = Symbol.for("transformed");
    // prevent duplicate broadcast
    readonly "@loadEventBroadcastedFlag" = Symbol.for("loadEventBroadcasted");

    // ...

    protected applyEntityTransformationToCursor<Entity extends ObjectLiteral>(
        metadata: EntityMetadata,
        cursor: FindCursor<Entity> | AggregationCursor<Entity>,
    ) {
        const queryRunner = this.mongoQueryRunner

        ;(cursor as any)["__to_array_func"] = cursor.toArray
        cursor.toArray = async () =>
            ((cursor as any)["__to_array_func"] as CallableFunction)().then(
                async (results: Entity[]) => {
                    const transformer = new DocumentToEntityTransformer()
                    const entities = results.map((result) => {
                        if (Reflect.get(result, this["@transformedFlag"])) {
                            return result
                        }
                        const entity = transformer.transform(result, metadata)
                        Reflect.set(entity, this["@transformedFlag"], true)
                        return entity
                    })
                    // broadcast "load" events
                    const needBroadcastEntities = entities.filter(entity => !Reflect.get(entity, this["@loadEventBroadcastedFlag"]))
                    await queryRunner.broadcaster.broadcast(
                        "Load",
                        metadata,
                        needBroadcastEntities,
                    )
                    needBroadcastEntities.forEach(entity => {
                        Reflect.set(entity, this["@loadEventBroadcastedFlag"], true)
                    })
                    return entities
                },
            )
        ;(cursor as any)["__next_func"] = cursor.next
        cursor.next = async () =>
            ((cursor as any)["__next_func"] as CallableFunction)().then(
                async (result: Entity) => {
                    if (!result) {
                        return result
                    }
                    let entity: Entity
                    if (Reflect.get(result, this["@transformedFlag"])) {
                        entity = result
                    } else {
                        const transformer = new DocumentToEntityTransformer()
                        entity = transformer.transform(result, metadata)
                        Reflect.set(entity, this["@transformedFlag"], true)
                    }
                    if (!Reflect.get(entity, this["@loadEventBroadcastedFlag"])) {
                        // broadcast "load" events
                        await queryRunner.broadcaster.broadcast("Load", metadata, [
                            entity,
                        ])
                        Reflect.set(entity, this["@loadEventBroadcastedFlag"], true)
                    }
                    return entity
                },
            )
    }

    // ...

}

Request:

Could you please investigate this issue and provide guidance or a fix? If there's a workaround that can be implemented on the application side in the meantime, I'd appreciate any suggestions.

Thank you for your assistance!

Relevant Database Driver(s)

  • aurora-mysql
  • aurora-postgres
  • better-sqlite3
  • cockroachdb
  • cordova
  • expo
  • mongodb
  • mysql
  • nativescript
  • oracle
  • postgres
  • react-native
  • sap
  • spanner
  • sqlite
  • sqlite-abstract
  • sqljs
  • sqlserver

Are you willing to resolve this issue by submitting a Pull Request?

Yes, I have the time, but I don't know how to start. I would need guidance.

Activity

  1. vovas87 commented on Aug 17, 2025

    @vovas87

    Confirming this issue with find() method in TypeORM 0.3 + MongoDB

    I can confirm this issue exists in TypeORM 0.3 with MongoDB driver when using the find() method.

    Reproduction Case:

    // Immediately query the same entity type
    const messages = await messageRepository.find({ 
      where: { conversationId: new ObjectId(conversationId) } 
    });
    
    // in the case messages = [{message}]
    @EntitySubscriber()
    export class MessageSubscriber implements EntitySubscriberInterface<Message> {
    
      async afterLoad(entity: Message) {
        this.decryptMessage(entity); // Called twice for same entity = double decryption = data corruption
      }
    }

    Result: The first afterLoad correctly decrypts data from DB, but the second call tries to decrypt already-decrypted plaintext, causing data corruption.

    Environment:

    • TypeORM: 0.3.x
    • Database: MongoDB
    • Driver: mongodb
    • Node.js: 22.x

    The issue is that a single find() operation incorrectly triggers afterLoad multiple times on the same entity instance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions