Skip to content

fix(mongodb): use cursor.transform for doc to entity transformation and skip load broadcast in next if toArray - #11926

Merged
Cprakhar merged 8 commits into
typeorm:masterfrom
Cprakhar:fix/after-load-mongodb
Jun 18, 2026
Merged

Cprakhar merged 8 commits into
typeorm:masterfrom
Cprakhar:fix/after-load-mongodb

Conversation

@Cprakhar

@Cprakhar Cprakhar commented Jan 19, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #11091

The Problem

In the current MongoDB implementation, applyEntityTransformationToCursor modifies the driver's next() and toArray() methods. Because the MongoDB driver may internally call both methods on the same cursor instance (for example, during find operations), this leads to issue:

  • Duplicate Subscriber Events: The EntitySubscriberInterface.afterLoad method is triggered multiple times for the same database record because each patched method independently transforms the document and emits a "Load" event.

Description of Change

  • Use cursor.transform API instead of calling DocumentToEntityTransformer.transform/transformAll in overridden toArray/next — handles next() and toArray(). As transformDocument() is called internally by the toArray and next methods
  • Skip broadcasting in next as toArray calls it internally (If next is called alone, broadcast the load events.)
  • Added transform in typings.ts

Pull Request Checklist

  • Code is up to date with the master branch
  • This pull request links to relevant issues: Fixes #11091
  • There are new or updated tests that validate the changes (tests/**.test.ts)
  • Documentation has been updated to reflect this change (docs/docs/**.md) (N/A)

@Cprakhar
Cprakhar force-pushed the fix/after-load-mongodb branch from b08d6ba to d8136f2 Compare January 19, 2026 21:29
@pkg-pr-new

pkg-pr-new Bot commented Jan 19, 2026 •

Copy link
Copy Markdown
  • typeorm-sql-js-example

    npm i https://pkg.pr.new/typeorm@11926
    

commit: 55451c8

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jan 19, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (10) 📘 Rule violations (5) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Null transform truncates cursor 🐞 Bug ≡ Correctness
Description
applyEntityTransformationToCursor assigns cursor.transform to
DocumentToEntityTransformer.transform, which can return null for a document. The MongoDB cursor
typings in this repo explicitly warn that mapping a document to null causes the cursor to close
before iterating all documents, so results can be silently truncated in cases where transformation
yields null.
Code

src/entity-manager/MongoEntityManager.ts[R1316-1320]

Evidence
The cursor typings explicitly document that mapping a document to null closes the cursor early;
since cursor.transform is exactly such a mapping hook, returning null from
DocumentToEntityTransformer.transform can terminate iteration prematurely.

src/entity-manager/MongoEntityManager.ts[1308-1345]
src/query-builder/transformer/DocumentToEntityTransformer.ts[20-24]
src/query-builder/transformer/DocumentToEntityTransformer.ts[141-144]
src/driver/mongodb/typings.ts[174-205]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`cursor.transform` is set to `transformer.transform(...)`, but `DocumentToEntityTransformer.transform` can return `null`. MongoDB cursor typings in this repo state that mapping to `null` will cause a cursor to close before finishing iteration, which can truncate `toArray()`, `next()`, and async iteration results.
### Issue Context
`DocumentToEntityTransformer.transform` returns `null` when it decides the document has no mapped data (`hasData` stays false). This is a legitimate outcome (e.g., certain projections / aggregation `$project` stages), but feeding that `null` into cursor-level transform is unsafe per the driver typings.
### Fix Focus Areas
- src/entity-manager/MongoEntityManager.ts[1308-1345]
- src/query-builder/transformer/DocumentToEntityTransformer.ts[20-24]
- src/query-builder/transformer/DocumentToEntityTransformer.ts[141-144]
- src/driver/mongodb/typings.ts[174-205]
### Suggested fix approach
- Ensure the function assigned to `cursor.transform` never returns `null`.
- Option A (most explicit): wrap the transformer result and return a non-null placeholder entity (e.g., `metadata.create(undefined, { fromDeserializer: true })`) when the transformer returns `null`.
- Option B: adjust `DocumentToEntityTransformer.transform` (or provide a new method used only by Mongo cursor transforms) to return an entity instance even when `hasData` is false.
- Add a regression test that forces `transformer.transform` to return `null` for at least one document (e.g., an `aggregateEntity` pipeline with a `$project` that removes `_id` and all mapped columns) and assert `toArray()` still returns the correct number of results and does not terminate early.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. queryrunner parameter misnamed 📘 Rule violation ⚙ Maintainability
Description
The new helper methods introduce a queryrunner parameter that violates the file/project’s
established camelCase naming (queryRunner). This reduces consistency and increases maintenance
friction when scanning for runner usage.
Code

src/entity-manager/MongoEntityManager.ts[1455]

Evidence
The naming-conventions rule requires new identifiers to follow established patterns. The newly added
parameter queryrunner deviates from typical camelCase used elsewhere (e.g.,
this.mongoQueryRunner).

Rule 1: Consistent Naming Conventions
src/entity-manager/MongoEntityManager.ts[1455-1455]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`queryrunner` is newly introduced and deviates from the project’s camelCase naming conventions.
## Issue Context
This parameter is used to broadcast `Load` events; consistent naming improves readability and maintainability.
## Fix Focus Areas
- src/entity-manager/MongoEntityManager.ts[1449-1493]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Async iteration untransformed 🐞 Bug ≡ Correctness
Description
MongoEntityCursor only overrides toArray and next when those properties are read, so async
iteration (e.g., for await (...)) uses the underlying cursor’s [Symbol.asyncIterator]() and
yields raw documents without entity transformation or Load broadcasts. This breaks the documented
guarantee that createEntityCursor “transforms each result into Entity model.”
Code

src/entity-manager/MongoEntityManager.ts[R1455-1468]

Evidence
createEntityCursor/aggregateEntity are documented to return a modified cursor that transforms
each result into an entity, but the proxy only intercepts string properties "toArray" and "next"
and forwards all other methods by invoking them on the underlying cursor (`apply(this.cursor,
...)). MongoDB cursors also expose async iteration via [Symbol.asyncIterator]()` (and other
iteration helpers like forEach), so using these APIs will bypass the proxy’s transformation
methods and return raw documents.

src/entity-manager/MongoEntityManager.ts[436-468]
src/entity-manager/MongoEntityManager.ts[1451-1470]
src/entity-manager/MongoEntityManager.ts[1455-1468]
src/driver/mongodb/typings.ts[128-166]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`MongoEntityCursor` only guarantees transformation/broadcasting for direct `cursor.next()` and `cursor.toArray()` calls. When consumers iterate using `for await (const x of cursor)` (which relies on `cursor[Symbol.asyncIterator]()`), the proxy forwards the async iterator implementation from the underlying MongoDB cursor, so yielded values are *not* passed through `DocumentToEntityTransformer` and do not trigger `Load` broadcasts.
### Issue Context
- `createEntityCursor` is documented as returning a cursor that “transforms each result into Entity model”.
- MongoDB cursors expose `[Symbol.asyncIterator]()` (and other iteration helpers), so it’s reasonable for users/tests to iterate using async iteration.
### Fix Focus Areas
- Implement a proxy override for `Symbol.asyncIterator` that yields values via the proxy’s `next()` (so transformation + broadcasting occurs per element).
- Optionally also override `forEach` to iterate using the proxied async iterator.
Fix focus locations:
- src/entity-manager/MongoEntityManager.ts[1451-1470]
- src/entity-manager/MongoEntityManager.ts[1492-1507]
- src/driver/mongodb/typings.ts[128-166]
### Suggested implementation sketch
- In the proxy `get` trap, add:
- `if (property === Symbol.asyncIterator) return this.asyncIterator.bind(this)`
- Add a method like:
- `private async *asyncIterator() { while (true) { const v = await this.next(); if (v === null) return; yield v; } }`
This ensures all iteration paths produce entities and fire `Load` events consistently.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View more (11)
4. Broadcasts null entities 🐞 Bug ≡ Correctness
Description
MongoEntityCursor.toArray() broadcasts the Load event with the raw transformAll() output, which can
include null entries, and Broadcaster will call afterLoad / hasOwnProperty on those entries. This
can throw at runtime and break MongoDB cursor loads for projections that yield documents with no
mapped entity data.
Code

src/entity-manager/MongoEntityManager.ts[R1476-1487]

Evidence
MongoEntityCursor.toArray() broadcasts whatever transformAll returns, without filtering.
DocumentToEntityTransformer.transform returns null when it cannot populate any entity data
(hasData=false), so transformAll can produce null entries. Broadcaster.broadcastLoadEvent iterates
the entities array and uses entity.hasOwnProperty(...) and calls subscriber.afterLoad(entity, ...)
without null checks, which will throw if an element is null.

src/entity-manager/MongoEntityManager.ts[1476-1487]
src/query-builder/transformer/DocumentToEntityTransformer.ts[146-149]
src/subscriber/Broadcaster.ts[933-945]
src/subscriber/Broadcaster.ts[972-985]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`MongoEntityCursor.toArray()` may broadcast `Load` with `null` entries because `DocumentToEntityTransformer.transform()` can return `null`. `Broadcaster.broadcastLoadEvent()` assumes entries are objects and may throw when it touches `hasOwnProperty` or calls `afterLoad`.
### Issue Context
- `DocumentToEntityTransformer.transform()` returns `null` when `hasData` is false.
- `MongoEntityCursor.next()` already avoids broadcasting when the transformed entity is `null`, but `toArray()` does not.
### Fix Focus Areas
- src/entity-manager/MongoEntityManager.ts[1476-1489]
- src/query-builder/transformer/DocumentToEntityTransformer.ts[146-149]
- src/subscriber/Broadcaster.ts[933-985]
### Implementation guidance
- In `toArray()`, filter out `null` entities before broadcasting.
- Consider returning only non-null entities to match the declared return type `Promise<Entity[]>`.
- Only call `broadcast("Load", ...)` when there is at least one non-null entity.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


5. Falsy next() treated exhausted 🐞 Bug ≡ Correctness
Description
applyEntityTransformationToCursor treats any falsy originalNext() result as cursor exhaustion
(return null), which is incorrect when the cursor is transformed to yield valid falsy values. This
can prematurely terminate iteration and clear the identity map even though more results exist.
Code

src/entity-manager/MongoEntityManager.ts[R1262-1266]

Evidence
MongoDB cursor typings explicitly state that cursors use null as the sentinel for exhaustion and
that mapping can produce other falsy values (e.g., empty string) as valid results; therefore
checking if (!result) is too broad and will mis-handle such values.

src/entity-manager/MongoEntityManager.ts[1262-1266]
src/driver/mongodb/typings.ts[138-165]
src/driver/mongodb/typings.ts[174-200]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`cursor.next` currently treats any falsy `result` as cursor exhaustion (`if (!result) ... return null`). Mongo cursors use **`null`** as the exhaustion sentinel, while other falsy values can be valid (e.g. after `cursor.map(() => '')`). This causes premature termination and incorrect cache clearing.
### Issue Context
This code is monkey-patching MongoDB cursor methods; it should preserve the cursor contract that only `null` indicates “no more documents”.
### Fix Focus Areas
- src/entity-manager/MongoEntityManager.ts[1262-1266]
### Suggested change
- Replace `if (!result)` with `if (result == null)` (or strict `result === null` if you want to follow the typing contract exactly).
- Only clear `entityCache` on true exhaustion.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


6. Falsy IDs skip cache 🐞 Bug ≡ Correctness
Description
In applyEntityTransformationToCursor, cursor.next() computes idStr using a truthy check
(documentId ? ...), so valid falsy IDs (e.g. 0 or empty string) won’t be cached/deduped. This
can re-trigger Load broadcasts for the same record and breaks consistency with the toArray()
path which uses an explicit null/undefined check.
Code

src/entity-manager/MongoEntityManager.ts[R1271-1276]

Evidence
toArray() treats any non-null/undefined ID as cacheable, but next() treats falsy IDs as
uncacheable, causing diverging behavior between the two patched methods for the same _id value.

src/entity-manager/MongoEntityManager.ts[1230-1235]
src/entity-manager/MongoEntityManager.ts[1271-1275]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`cursor.next()` currently derives `idStr` via a truthy check (`documentId ? ...`), which incorrectly treats valid falsy IDs as missing and bypasses caching/deduplication.
### Issue Context
`toArray()` already uses an explicit `documentId !== null && documentId !== undefined` check; `next()` should match this behavior.
### Fix Focus Areas
- src/entity-manager/MongoEntityManager.ts[1271-1279]
- src/entity-manager/MongoEntityManager.ts[1231-1235]
### Implementation notes
- Change `const idStr = documentId ? ...` to a nullish check consistent with `toArray()`.
- Keep the `if (idStr !== undefined && entityCache.has(idStr))` style to avoid truthiness pitfalls.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


7. Cache key collisions 🐞 Bug ≡ Correctness
Description
The identity map keys entities by documentId.toString(), which can collapse distinct _id values
into the same string (e.g., objects become "[object Object]"), causing incorrect entity reuse and
suppressed Load broadcasts. MongoDB typings in this repo allow _id to be any type via
InferIdType, so non-primitive ids are supported by the type system.
Code

src/entity-manager/MongoEntityManager.ts[R1172-1176]

Evidence
The cache key is derived by toString() on the _id value and stored in Map. MongoDB typings
define _id as InferIdType, which is whatever type the schema uses; this can be an object. For
object ids, toString() is not a stable unique serialization, so distinct ids can collide and
return the wrong cached entity reference.

src/entity-manager/MongoEntityManager.ts[1171-1176]
src/entity-manager/MongoEntityManager.ts[1208-1216]
src/driver/mongodb/typings.ts[6957-6960]
src/driver/mongodb/typings.ts[4001-4014]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The cursor identity map uses `documentId.toString()` as a `Map&lt;string, Entity&gt;` key. For non-primitive ids (e.g., object `_id`), this can collide (&quot;[object Object]&quot;) and cause wrong entity reuse + missing Load broadcasts.
### Issue Context
MongoDB typings in this repo allow `_id` to be any type (`InferIdType&lt;TSchema&gt;`), so `_id` values are not guaranteed to stringify uniquely.
### Fix Focus Areas
- src/entity-manager/MongoEntityManager.ts[1171-1183]
- src/entity-manager/MongoEntityManager.ts[1208-1216]
### Implementation notes
- Prefer a deterministic BSON-aware serialization for keys (e.g., `EJSON.stringify(documentId)` from the MongoDB BSON package, or `BSON.serialize(documentId)` then base64) and prefix with a type tag.
- Alternatively, branch by common id types: ObjectId =&gt; hex string; primitives =&gt; `${typeof id}:${String(id)}`; objects =&gt; canonical JSON/EJSON.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


8. Cached entities skip Load event broadcast 🐞 Bug ≡ Correctness
Description
• When entities are retrieved from entityCache, the Load event is not broadcast to subscribers,
breaking the entity subscriber contract • Subscribers relying on afterLoad hooks for initialization,
auditing, or transformation will miss cached entity loads • This causes incomplete audit logs,
uninitialized lazy-loaded relationships, and skipped custom entity transformations • The old code
always broadcast Load events for all entities, ensuring subscribers were notified for every load
Code

src/entity-manager/MongoEntityManager.ts[R1058-1061]

Evidence
The new code returns cached entities without broadcasting Load events. In toArray at lines
1058-1061, when entityCache.has(idStr) is true, the cached entity is pushed to results and the
function returns early, skipping the broadcaster call at lines 1070-1076 which only broadcasts for
newlyLoadedEntities. Similarly in next at lines 1097-1099, cached entities are returned without
broadcasting. The old code at lines 1046-1049 always broadcast Load events for all entities. The
test subscriber at MockSubscriber.ts expects afterLoad to be called for each entity load, and the
Broadcaster.ts implementation at lines 878-885 shows that afterLoad is invoked for each entity in
the broadcast.

src/entity-manager/MongoEntityManager.ts[1058-1061]
src/entity-manager/MongoEntityManager.ts[1070-1076]
src/entity-manager/MongoEntityManager.ts[1097-1099]
test/functional/mongodb/basic/entity-subscriber/subscriber/MockSubscriber.ts[16-18]
src/subscriber/Broadcaster.ts[878-885]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
# Issue Description
Cached entities bypass the broadcaster, breaking the entity subscriber contract. When entities are retrieved from entityCache, no Load event is broadcast, causing subscribers to miss afterLoad notifications.
# Issue Context
The PR introduces entity caching to deduplicate entities within a cursor&amp;#x27;s lifetime. However, the optimization incorrectly assumes that cached entities don&amp;#x27;t need Load events. Entity subscribers expect afterLoad to be called for every entity load operation, regardless of whether the entity comes from cache or database.
# Fix Focus Areas
- src/entity-manager/MongoEntityManager.ts[1058-1061] - toArray cached entity return path
- src/entity-manager/MongoEntityManager.ts[1097-1099] - next cached entity return path
- src/entity-manager/MongoEntityManager.ts[1070-1076] - broadcaster call that only handles newlyLoadedEntities
Options:
1. Remove caching optimization entirely and always broadcast for all entities
2. Keep caching but broadcast Load events for cached entities before returning them
3. Track which cached entities have been broadcast and only broadcast once per unique entity

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


9. Cursor patch uses any 📘 Rule violation ≡ Correctness
Description
applyEntityTransformationToCursor introduces any types for cursor results, bypassing type safety
and making it easier to miss incorrect document/entity shapes. This violates the requirement to
avoid any casts used to bypass typing issues.
Code

src/entity-manager/MongoEntityManager.ts[R1158-1207]

Evidence
PR Compliance ID 4 forbids adding any casts/types to bypass type issues; the updated cursor
monkey-patch explicitly types both toArray and next results as any/any[].

Rule 4: Remove AI-generated noise
src/entity-manager/MongoEntityManager.ts[1158-1207]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`applyEntityTransformationToCursor` uses `any` for `results` and `result`, which bypasses type safety.
## Issue Context
The compliance checklist disallows adding `any` casts/types to sidestep typing problems.
## Fix Focus Areas
- src/entity-manager/MongoEntityManager.ts[1158-1207]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


10. afterLoad skipped in toArray 🐞 Bug ≡ Correctness
Description
cursor.toArray() only broadcasts Load for entities with a truthy documentId, so projected
documents without _id (or falsy IDs) can be returned without triggering afterLoad
listeners/subscribers.
Code

src/entity-manager/MongoEntityManager.ts[R1172-1193]

Evidence
toArray() computes idStr from a truthy check and only adds entities to newlyLoadedEntities
when idStr is truthy; it then broadcasts only when newlyLoadedEntities.length > 0. Meanwhile,
the transformer can return an entity even when documentId is undefined (e.g., when _id was
projected out), and MongoDB cursors support projections excluding _id, meaning this path is
reachable and would skip afterLoad broadcast entirely.

src/entity-manager/MongoEntityManager.ts[1148-1196]
src/query-builder/transformer/DocumentToEntityTransformer.ts[29-35]
src/query-builder/transformer/DocumentToEntityTransformer.ts[235-236]
src/driver/mongodb/typings.ts[3403-3408]
src/subscriber/Broadcaster.ts[891-907]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`applyEntityTransformationToCursor`’s `toArray()` wrapper only broadcasts `Load` for entities where `documentId` becomes a truthy string key. This causes `afterLoad` listeners/subscribers to not run at all for documents where `_id` is not present (e.g. cursor projection `{ _id: 0, ... }`) or where `_id` is a valid but falsy value.
### Issue Context
- `DocumentToEntityTransformer.transform()` can return `{ entity, documentId }` with `documentId` derived from `document._id`, which can be `undefined` when `_id` is projected out.
- MongoDB cursors support projections that exclude `_id`.
### Fix Focus Areas
- src/entity-manager/MongoEntityManager.ts[1158-1193]
### Suggested approach
- Compute an ID key with `documentId !== null &amp;amp;&amp;amp; documentId !== undefined` checks.
- Treat entities without an ID as &amp;quot;always newly loaded&amp;quot; (cannot be cached), so they should still be included in the broadcast payload.
- Broadcast `Load` for all entities that are either:
- not found in the cache (cacheable IDs), or
- not cacheable (no ID).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


11. console.log statement in test code 📘 Rule violation ≡ Correctness
Description
• The test file contains a console.log(loadedPosts.length) statement at line 321 • This appears to
be a debug statement that should be removed before merging • Debug logging statements should not be
committed to the codebase
Code

test/functional/mongodb/basic/mongo-repository/mongo-repository.test.ts[321]

Evidence
The compliance rule requires removing AI-generated noise and debug code. While console.log
statements exist in some test files for intentional output (like sample apps), this particular
instance appears to be a leftover debug statement since it logs a value that is immediately asserted
in the next line. The test already validates the length with
expect(loadedPosts).to.have.length(10), making the console.log redundant.

Rule 4: Remove AI-generated noise
test/functional/mongodb/basic/mongo-repository/mongo-repository.test.ts[321-321]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A debug `console.log` statement was left in the test code that should be removed.
## Issue Context
The console.log statement at line 321 logs `loadedPosts.length` which is immediately verified by the assertion on line 322. This appears to be a leftover debug statement.
## Fix Focus Areas
- test/functional/mongodb/basic/mongo-repository/mongo-repository.test.ts[321-321]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


12. Documentation not updated for PR 📘 Rule violation ≡ Correctness
Description
• The PR introduces a significant change to MongoDB entity subscriber behavior (fixing duplicate
afterLoad events) which is a user-facing change. • The PR description explicitly marks
documentation as not updated: `[ ] Documentation has been updated to reflect this change
(docs/docs/**.md)`. • The MongoDB documentation (docs/docs/drivers/mongodb.md) and
listeners/subscribers documentation (docs/docs/advanced-topics/4-listeners-and-subscribers.md) do
not mention this fix or the new behavior regarding identity mapping and cursor-level caching.
Code

src/entity-manager/MongoEntityManager.ts[R1038-1108]

Evidence
The PR Compliance Checklist requires documentation updates for user-facing changes (PR Compliance ID
2). The PR description explicitly states documentation has NOT been updated (checkbox unchecked),
and the code changes fix a significant bug affecting how entity subscribers work with MongoDB
cursors. This is a user-facing behavioral change that should be documented.

Rule 2: Docs updated for user-facing changes
src/entity-manager/MongoEntityManager.ts[1038-1108]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The PR fixes a significant bug where MongoDB entity subscriber `afterLoad` methods were called multiple times for the same document. This is a user-facing behavioral change that needs to be documented.
## Issue Context
The fix introduces cursor-level identity mapping to ensure that:
1. Entity instances are cached per cursor lifecycle
2. `afterLoad` subscribers are only called once per unique document
3. The same object reference is returned when a document is encountered multiple times
This behavior should be documented so users understand how entity subscribers work with MongoDB cursors.
## Fix Focus Areas
- docs/docs/drivers/mongodb.md[1-500]
- docs/docs/advanced-topics/4-listeners-and-subscribers.md[1-400]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


13. Cache Bypass When DocumentId Undefined 🐞 Bug ≡ Correctness
Description
• When documentId is undefined (no _id field or objectIdColumn mapping fails), entities are never
cached • This defeats the entire purpose of the caching mechanism and causes duplicate broadcaster
calls for the same document • The issue occurs silently without any warning or error, making it
difficult to detect
Code

src/entity-manager/MongoEntityManager.ts[R1056-1067]

Evidence
The code only caches entities when idStr is defined (line 1064). If documentId is undefined from the
transformer, idStr becomes undefined and the entity is added to results without caching. This means
duplicate documents will create duplicate entity instances and trigger broadcaster multiple times.
The documentId can be undefined if the document has no _id or if objectIdColumn is not configured.

src/entity-manager/MongoEntityManager.ts[1056-1067]
src/query-builder/transformer/DocumentToEntityTransformer.ts[34-56]
src/entity-manager/MongoEntityManager.ts[1095-1102]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
When documentId is undefined, the caching mechanism is silently bypassed, causing duplicate broadcaster calls and defeating the purpose of the cache.
## Issue Context
MongoDB documents should always have an _id field, but the code doesn&amp;amp;#x27;t enforce this. When documentId is undefined, the entity is never cached (lines 1064-1067 and 1100-1102), leading to duplicate entity instances.
## Fix Focus Areas
- src/entity-manager/MongoEntityManager.ts[1056-1067]
- src/entity-manager/MongoEntityManager.ts[1095-1102]
Add validation after getting documentId:

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


14. Cached Entities Skip Load Event Broadcasting ✓ Resolved 🐞 Bug ≡ Correctness
Description
• When an entity is found in the cache, it's returned without triggering the broadcaster's 'Load'
event, breaking entity subscribers • In toArray(), cached entities are pushed to results (line 1059)
without being added to newlyLoadedEntities, so they skip broadcasting (lines 1070-1076) • In next(),
cached entities return early (line 1098) before the broadcast call (lines 1103-1105) • This violates
the contract that afterLoad hooks should be called for every entity load operation, causing silent
failures in applications relying on these hooks for logging, cache invalidation, or other side
effects
Code

src/entity-manager/MongoEntityManager.ts[R1058-1060]

Evidence
The code shows that cached entities are returned without broadcasting. In toArray(), lines 1058-1060
show cached entities being pushed directly to the results array and returning early. Only
newlyLoadedEntities trigger the Load event at lines 1070-1076. Similarly, in next() at lines
1097-1098, cached entities return immediately, bypassing the broadcast at lines 1103-1105. The test
at mongo-subscriber.test.ts lines 55-76 expects afterLoad to be called 3 times for 3 entities, but
doesn't test the scenario where the same entity is loaded multiple times.

src/entity-manager/MongoEntityManager.ts[1058-1060]
src/entity-manager/MongoEntityManager.ts[1070-1076]
src/entity-manager/MongoEntityManager.ts[1097-1098]
src/subscriber/Broadcaster.ts[820-824]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
Cached entities are returned without triggering the broadcaster&amp;amp;#x27;s &amp;amp;#x27;Load&amp;amp;#x27; event, breaking the contract for entity subscribers that expect afterLoad hooks to be called for every entity load operation.
## Issue Context
The PR introduces entity caching to ensure reference equality when the same document appears multiple times in cursor results. However, the optimization inadvertently skips the Load event broadcasting for cached entities, causing silent failures in applications that rely on afterLoad hooks.
## Fix Focus Areas
- src/entity-manager/MongoEntityManager.ts[1058-1076] - toArray() method: ensure all entities (cached and new) are included in the broadcast
- src/entity-manager/MongoEntityManager.ts[1097-1108] - next() method: ensure cached entities also trigger the Load event before returning

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

15. AnotherMockSubscriber uses any 📘 Rule violation ⚙ Maintainability
Description
New test subscriber code introduces any types (EntitySubscriberInterface, entity: any,
LoadEvent), which weakens type-safety and appears to bypass typing rather than model the intended
contract. This violates the requirement to avoid any-based type escapes in new changes.
Code

test/functional/mongodb/basic/entity-subscriber/subscriber/MockSubscriber.ts[R22-25]

Evidence
PR Compliance ID 4 forbids introducing any type escapes in new changes. The added
AnotherMockSubscriber explicitly uses any in its subscriber interface and method signature.

Rule 4: Remove AI-generated noise
test/functional/mongodb/basic/entity-subscriber/subscriber/MockSubscriber.ts[22-25]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
New test code uses `any` in `AnotherMockSubscriber`, which reduces type-safety and violates the compliance rule to avoid `any` casts/types used to bypass typing issues.
## Issue Context
`AnotherMockSubscriber` doesn't use the entity value (it only increments a counter), so it can be typed safely without `any`.
## Fix Focus Areas
- test/functional/mongodb/basic/entity-subscriber/subscriber/MockSubscriber.ts[22-25]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


16. Subscriber index brittle 🐞 Bug ☼ Reliability
Description
The new MongoDB subscriber tests assume dataSource.subscribers[0] and [1] correspond to specific
subscriber classes. Subscriber ordering is produced by filtering the global metadata args storage
and is not guaranteed to match the input array order, making the tests fragile and potentially
flaky.
Code

test/functional/mongodb/basic/entity-subscriber/mongo-subscriber.test.ts[R26-33]

Evidence
The test uses subscriber indices, but the DataSource subscriber list is constructed by filtering the
global metadata subscriber list (order from registration), not by preserving the passed-in order, so
the index is not a stable identifier.

test/functional/mongodb/basic/entity-subscriber/mongo-subscriber.test.ts[26-33]
src/data-source/DataSource.ts[714-726]
src/connection/ConnectionMetadataBuilder.ts[55-73]
src/metadata-args/MetadataArgsStorage.ts[325-334]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The tests access subscribers using fixed indexes (`subscribers[0]`, `subscribers[1]`). The subscribers array is built from metadata storage filtering, which preserves metadata registration order rather than the order provided in the test setup, so these index assumptions are brittle.
### Issue Context
`DataSource.buildMetadatas()` assigns `this.subscribers` from `ConnectionMetadataBuilder.buildSubscribers()`, which uses `getMetadataArgsStorage().filterSubscribers(...).map(...)`. `filterSubscribers` relies on a target filter over the metadata storage array and preserves that array's existing order.
### Fix Focus Areas
- test/functional/mongodb/basic/entity-subscriber/mongo-subscriber.test.ts[26-33]
- src/data-source/DataSource.ts[714-726]
- src/connection/ConnectionMetadataBuilder.ts[55-73]
- src/metadata-args/MetadataArgsStorage.ts[325-334]
### Suggested fix approach
- Replace index-based access with type-based lookup:
- `const mockSubscriber = dataSources[0].subscribers.find(s => s instanceof MockSubscriber) as MockSubscriber;`
- `const anotherMockSubscriber = dataSources[0].subscribers.find(s => s instanceof AnotherMockSubscriber) as AnotherMockSubscriber;`
- Add assertions that the subscribers were found (non-undefined) to fail fast with a clear error if registration changes.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

  • Author self-review: I have reviewed the code review findings, and addressed the relevant ones.

Qodo Logo

@Cprakhar
Cprakhar marked this pull request as draft January 19, 2026 21:40
@Cprakhar Cprakhar changed the title fix(mongodb): improve applyEntityTransformationToCursor and remove redundant monkey patch on cursor.next() fix(mongodb): improve applyEntityTransformationToCursor method with correct monkey patch for toArray and next Jan 19, 2026
@Cprakhar
Cprakhar marked this pull request as ready for review January 20, 2026 07:31
@Cprakhar
Cprakhar force-pushed the fix/after-load-mongodb branch from 81ff8ca to 3898694 Compare January 20, 2026 07:36
@coveralls

coveralls commented Jan 20, 2026 •

Copy link
Copy Markdown

Coverage Status

coverage: 73.68% (-0.07%) from 73.745% — Cprakhar:fix/after-load-mongodb into typeorm:master

@Cprakhar
Cprakhar force-pushed the fix/after-load-mongodb branch from 34cf0c3 to 6d98759 Compare January 20, 2026 09:01

@gioboa gioboa left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks great to me, you rock 👏 @Cprakhar

@gioboa

gioboa commented Jan 27, 2026

Copy link
Copy Markdown
Collaborator

/review

@Cprakhar
Cprakhar force-pushed the fix/after-load-mongodb branch from 6d98759 to a0b14ae Compare February 24, 2026 09:34
@Cprakhar
Cprakhar force-pushed the fix/after-load-mongodb branch from a0b14ae to 77f23fb Compare March 13, 2026 15:18
@Cprakhar
Cprakhar force-pushed the fix/after-load-mongodb branch 4 times, most recently from ce8f646 to df5da01 Compare April 2, 2026 15:33
@Cprakhar Cprakhar changed the title fix(mongodb): improve applyEntityTransformationToCursor method with correct monkey patch for toArray and next fix(mongodb): replace monkey-patch cursor toArray and next methods with proxy pattern Apr 10, 2026
@Cprakhar
Cprakhar force-pushed the fix/after-load-mongodb branch from df5da01 to 7d637db Compare April 10, 2026 13:06
@Cprakhar
Cprakhar requested a review from gioboa April 10, 2026 13:26
@Cprakhar
Cprakhar marked this pull request as draft April 10, 2026 13:39
@Cprakhar
Cprakhar force-pushed the fix/after-load-mongodb branch from eda1d57 to d49d514 Compare April 10, 2026 14:44
@Cprakhar Cprakhar changed the title fix(mongodb): replace monkey-patch cursor toArray and next methods with proxy pattern fix(mongodb): call original next in monkey-patched toArray method Apr 10, 2026
@Cprakhar
Cprakhar marked this pull request as ready for review April 10, 2026 14:52
@Cprakhar
Cprakhar force-pushed the fix/after-load-mongodb branch from d49d514 to 79ff557 Compare April 10, 2026 15:16
@sonarqubecloud

Copy link
Copy Markdown

@Cprakhar Cprakhar changed the title fix(mongodb): call original next in monkey-patched toArray method fix(mongodb): use cursor.transform for doc to entity transformation and skip load broadcast in next if toArray Apr 30, 2026
@Cprakhar
Cprakhar requested a review from alumni May 4, 2026 20:27
@alonesuperman

Copy link
Copy Markdown

When will it be merged?

if (entities.length > 0) {
await broadcaster.broadcast("Load", metadata, entities)
}
return entities

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

any errors that should bubble up to user

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cursor.toArray = async () => {
    isInToArray = true
    try {
        const entities = await originalToArray()
        if (entities.length > 0) {
            await broadcaster.broadcast("Load", metadata, entities)
        }
        return entities
    } catch (e) {
        // if broadcast fails, still return entities?
        // or re-throw?
    } finally {
        isInToArray = false
    }
}

trying to understand - need to spin up a mongodb instance to give this a try, but given the tests is a scenario covered where we show how that will work?

@smith-xyz smith-xyz left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

just a minor note - but it seems to be an existing issue from before, let me know if I'm missing something in that comment

if (entities.length > 0) {
await broadcaster.broadcast("Load", metadata, entities)
}
return entities

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cursor.toArray = async () => {
    isInToArray = true
    try {
        const entities = await originalToArray()
        if (entities.length > 0) {
            await broadcaster.broadcast("Load", metadata, entities)
        }
        return entities
    } catch (e) {
        // if broadcast fails, still return entities?
        // or re-throw?
    } finally {
        isInToArray = false
    }
}

trying to understand - need to spin up a mongodb instance to give this a try, but given the tests is a scenario covered where we show how that will work?

@Cprakhar
Cprakhar merged commit 0bbefc9 into typeorm:master Jun 18, 2026
46 checks passed
@github-actions github-actions Bot added this to the 1.0 milestone Jun 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Development

Successfully merging this pull request may close these issues.

Duplicate afterLoad Event Triggered in MongoDB Driver when Using findOne

7 participants