Skip to content

fix(mongo): correctly process embedded arrays of nested documents - #10940

Merged
gioboa merged 2 commits into
typeorm:masterfrom
mciuchitu:fix/mongodb-arrays
Jan 5, 2026
Merged

gioboa merged 2 commits into
typeorm:masterfrom
mciuchitu:fix/mongodb-arrays

Conversation

@mciuchitu

@mciuchitu mciuchitu commented Jun 20, 2024 •

Copy link
Copy Markdown
Contributor

Description of change

These changes fix the issue with embedded array update in MongoDB.

Pull-Request Checklist

  • Code is up-to-date with the master branch
  • npm run format to apply prettier formatting
  • npm run test passes with this change
  • This pull request links relevant issues as Fixes #0000
  • There are new or updated unit tests validating the change
  • Documentation has been updated to reflect this change
  • The new commits follow conventions explained in CONTRIBUTING.md

Summary by CodeRabbit

  • New Features

    • Added support for nested embedded objects within array columns in MongoDB entities, allowing for more complex data structures.
  • Tests

    • Enhanced test coverage to verify correct persistence, retrieval, and updating of nested embedded objects within array columns.
    • Introduced a new entity for color information and updated related test entities and assertions accordingly.
  • Refactor

    • Improved internal handling of embedded metadata to better support arrays and nested structures.

@mciuchitu
mciuchitu force-pushed the fix/mongodb-arrays branch from f0ad0ac to a82b1ae Compare June 21, 2024 08:41
@mciuchitu mciuchitu changed the title fix: process correctly embedded arrays of nested documents for mongodb Process correctly embedded arrays of nested documents for mongodb Jun 21, 2024
@mciuchitu mciuchitu changed the title Process correctly embedded arrays of nested documents for mongodb Process correctly embedded arrays of nested documents for MongoDB Jun 21, 2024
@mciuchitu
mciuchitu force-pushed the fix/mongodb-arrays branch from a82b1ae to b1f1c4d Compare June 24, 2024 14:42
@mciuchitu

Copy link
Copy Markdown
Contributor Author

@pleerock @NoNameProvided sorry to ping you but may I ask you please to review this PR?

@mciuchitu
mciuchitu force-pushed the fix/mongodb-arrays branch from 4263b69 to bb0bf2e Compare March 12, 2025 11:39
@mciuchitu
mciuchitu force-pushed the fix/mongodb-arrays branch from bb0bf2e to cec9f3e Compare April 22, 2025 10:15
@mciuchitu
mciuchitu force-pushed the fix/mongodb-arrays branch from cec9f3e to 3ea8a88 Compare June 3, 2025 10:20
@coderabbitai

coderabbitai Bot commented Jun 3, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

The changes refactor the logic for extracting embedded column values in ColumnMetadata to handle complex embedded metadata hierarchies, including arrays and nested embeds. Additionally, a new Color class is introduced and integrated as a nested embedded object within Counters. Related MongoDB tests are enhanced to verify correct persistence and retrieval of these nested structures.

Changes

File(s) Change Summary
src/metadata/ColumnMetadata.ts Refactored getEntityValueMap to use embeddedMetadataTree for extracting nested embedded column values; minor comment formatting fix.
test/functional/mongodb/basic/array-columns/entity/Color.ts Added new Color class with a name property and constructor.
test/functional/mongodb/basic/array-columns/entity/Counters.ts Added color: Color property, updated constructor, and imported Color.
test/functional/mongodb/basic/array-columns/mongodb-array-columns.ts Enhanced tests to create/use Color objects in Counters, and added assertions for nested embedded persistence and retrieval.

Sequence Diagram(s)

sequenceDiagram
    participant TestSuite
    participant Post
    participant Counters
    participant Color
    participant MongoDB

    TestSuite->>Post: Create Post with Counters[]
    loop For each Counter
        TestSuite->>Color: Create Color(name)
        TestSuite->>Counters: Create Counters(..., color: Color)
        Post->>Counters: Embed Counters (with Color)
    end
    TestSuite->>MongoDB: Save Post
    MongoDB-->>TestSuite: Post with nested Counters and Colors

    TestSuite->>MongoDB: Retrieve Post
    MongoDB-->>TestSuite: Post with Counters[] (each with Color)
    TestSuite->>Counters: Assert color is instance of Color
Loading

Poem

In the garden of code where columns grow deep,
Now colors nestle in counters, no secrets to keep.
Metadata trees branch, arrays intertwine,
MongoDB tests sparkle—everything’s fine!
With every new embed, the data hops bright,
A rabbit’s delight in code done right.
🐇🌈

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

npm error Exit handler never called!
npm error This is an error with npm itself. Please report this error at:
npm error https://github.com/npm/cli/issues
npm error A complete log of this run can be found in: /.npm/_logs/2025-06-03T10_21_25_030Z-debug-0.log


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5003aaa and 3ea8a88.

📒 Files selected for processing (4)
  • src/metadata/ColumnMetadata.ts (3 hunks)
  • test/functional/mongodb/basic/array-columns/entity/Color.ts (1 hunks)
  • test/functional/mongodb/basic/array-columns/entity/Counters.ts (2 hunks)
  • test/functional/mongodb/basic/array-columns/mongodb-array-columns.ts (5 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
test/functional/mongodb/basic/array-columns/entity/Counters.ts (2)
src/decorator/columns/Column.ts (1)
  • Column (134-220)
test/functional/mongodb/basic/array-columns/entity/Color.ts (1)
  • Color (3-10)
test/functional/mongodb/basic/array-columns/mongodb-array-columns.ts (2)
test/functional/mongodb/basic/array-columns/entity/Counters.ts (1)
  • Counters (4-19)
test/functional/mongodb/basic/array-columns/entity/Color.ts (1)
  • Color (3-10)
🔇 Additional comments (16)
test/functional/mongodb/basic/array-columns/entity/Color.ts (1)

1-10: LGTM! Clean entity implementation.

The Color entity class is well-implemented with proper TypeORM decorators and a clean constructor pattern. This will serve effectively as a nested embedded object within the Counters entity.

test/functional/mongodb/basic/array-columns/entity/Counters.ts (3)

2-2: LGTM! Proper import for embedded entity.

The import statement correctly references the new Color entity class.


11-12: LGTM! Correct embedded column implementation.

The embedded color property is properly defined using @Column((type) => Color) syntax, which is the correct way to declare nested embedded objects in TypeORM.


14-17: LGTM! Constructor properly updated.

The constructor correctly accepts the new color parameter and initializes the property following established patterns in the class.

test/functional/mongodb/basic/array-columns/mongodb-array-columns.ts (7)

11-11: LGTM! Proper import addition.

The Color import is correctly added to support the enhanced test scenarios.


37-39: LGTM! Comprehensive test data setup.

The test correctly creates Counters instances with embedded Color objects, providing good test coverage for nested embedded structures in arrays.


81-87: LGTM! Thorough validation of nested embedded objects.

The assertions properly verify that:

  1. The color properties are correctly instantiated as Color objects
  2. The name properties retain their expected values after persistence

This validates that the embedded array processing works correctly for nested objects.


94-96: LGTM! Good test coverage for update scenarios.

The test properly validates update operations with different Color instances, ensuring that embedded array updates work correctly.


138-146: LGTM! Comprehensive validation after updates.

The assertions correctly verify that updated nested embedded objects maintain their structure and values after persistence operations.


151-152: LGTM! Complete test coverage for all array scenarios.

The test properly validates that the other1 array also correctly handles nested embedded Color objects, ensuring comprehensive coverage of the embedded array processing functionality.


165-167: LGTM! Metadata retrieval test properly updated.

The column metadata test correctly includes Color objects in the test data, ensuring that the metadata extraction functionality works properly with nested embedded structures.

src/metadata/ColumnMetadata.ts (5)

633-635: LGTM! Improved metadata tree handling.

The change from a simple propertyNames array to embeddedMetadataTree provides richer metadata information needed for proper embedded array processing. This is a key improvement for handling complex nested structures.


644-682: LGTM! Enhanced recursive extraction logic.

The refactored extractEmbeddedColumnValue function now properly handles embedded metadata trees with several key improvements:

  1. Richer metadata access: Uses EmbeddedMetadata objects instead of simple strings
  2. Array handling: Properly detects and processes arrays of embedded objects via embeddedMetadata.isArray
  3. Recursive mapping: Correctly maps over array elements when needed

This addresses the core issue described in the PR objective for processing embedded arrays correctly in MongoDB.


685-687: LGTM! Improved array handling for embedded arrays.

The logic correctly handles the case where the current level is an embedded array by mapping over elements and extracting the property value from each. This ensures embedded arrays are processed correctly.


699-699: LGTM! Consistent usage of metadata tree.

The function call correctly uses the new embeddedMetadataTree parameter, maintaining consistency with the refactored logic throughout the method.


707-707: LGTM! Minor formatting improvement.

The indentation fix improves code readability without affecting functionality.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@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.

is this PR still valid? can I ask you to solve the conflicts please?

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

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

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to c4243b4

CategorySuggestion                                                                                                                                    Impact
Possible issue
Handle null values in extraction function

Add a null check for the value parameter in the extractEmbeddedColumnValue
function to prevent potential runtime errors.

src/metadata/ColumnMetadata.ts [651-659]

 const extractEmbeddedColumnValue = (
     embeddedMetadataTree: EmbeddedMetadata[],
     value: ObjectLiteral,
 ): ObjectLiteral => {
-    if (value === undefined) {
+    if (value === undefined || value === null) {
         return {}
     }
 
     const embeddedMetadata = embeddedMetadataTree.at(0)
  • Apply / Chat
Suggestion importance[1-10]: 8

__

Why: This suggestion correctly identifies a potential TypeError if value is null, as the code would attempt to access a property on a null object. Adding the null check prevents this runtime error.

Medium
  • More

Previous suggestions

Suggestions up to commit 42bdbb3
CategorySuggestion                                                                                                                                    Impact
Possible issue
Handle null values in extraction

Update the initial guard clause in extractEmbeddedColumnValue to also check for
null values, not just undefined, to prevent runtime errors.

src/metadata/ColumnMetadata.ts [651-659]

 const extractEmbeddedColumnValue = (
     embeddedMetadataTree: EmbeddedMetadata[],
     value: ObjectLiteral,
 ): ObjectLiteral => {
-    if (value === undefined) {
+    if (value === undefined || value === null) {
         return {}
     }
 
     const embeddedMetadata = embeddedMetadataTree.at(0)
Suggestion importance[1-10]: 8

__

Why: This is a critical fix that prevents a runtime TypeError if a null value is passed to the recursive function. The current code only handles undefined, making this a valid and important bug fix.

Medium
Handle null/undefined array elements

Add a filter to remove null or undefined elements from embeddedPropertyValue
before mapping over it to prevent potential runtime errors during recursion.

src/metadata/ColumnMetadata.ts [665-678]

 if (
     embeddedMetadata.isArray &&
     Array.isArray(embeddedPropertyValue)
 ) {
     return {
-        [embeddedPropertyName]: embeddedPropertyValue.map(
-            (element) =>
-                extractEmbeddedColumnValue(
-                    embeddedMetadataTree.slice(1),
-                    element,
-                ),
-        ),
+        [embeddedPropertyName]: embeddedPropertyValue
+            .filter((element) => element !== undefined && element !== null)
+            .map(
+                (element) =>
+                    extractEmbeddedColumnValue(
+                        embeddedMetadataTree.slice(1),
+                        element,
+                    ),
+            ),
     }
 }
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies that a null element within the embeddedPropertyValue array would cause a runtime error, as the recursive function only checks for undefined. Filtering out null values prevents this potential crash.

Medium
Suggestions up to commit f6f9fda
CategorySuggestion                                                                                                                                    Impact
Possible issue
Handle null array elements safely

Filter out null or undefined elements from the embeddedPropertyValue array
before mapping over it to prevent potential runtime errors during recursive
processing.

src/metadata/ColumnMetadata.ts [665-678]

 if (
     embeddedMetadata.isArray &&
     Array.isArray(embeddedPropertyValue)
 ) {
     return {
-        [embeddedPropertyName]: embeddedPropertyValue.map(
-            (element) =>
-                extractEmbeddedColumnValue(
-                    embeddedMetadataTree.slice(1),
-                    element,
-                ),
-        ),
+        [embeddedPropertyName]: embeddedPropertyValue
+            .filter((element) => element != null)
+            .map(
+                (element) =>
+                    extractEmbeddedColumnValue(
+                        embeddedMetadataTree.slice(1),
+                        element,
+                    ),
+            ),
     }
 }
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies that iterating over an array with null or undefined elements would cause a runtime error in the recursive call, and the proposed fix using filter is an effective way to improve robustness.

Medium

@mciuchitu

Copy link
Copy Markdown
Contributor Author

Hi @gioboa! Yes, the updated tests still fail without the changes in the PR. I’ve rebased the branch

@pkg-pr-new

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

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

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

commit: c4243b4

@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.

Yes, the updated tests still fail without the changes in the PR. I’ve rebased the branch

Thank you 🙏

@gioboa
gioboa requested review from G0maa, alumni and naorpeled January 5, 2026 09:33
@gioboa gioboa changed the title Process correctly embedded arrays of nested documents for MongoDB fix: process correctly embedded arrays of nested documents for MongoDB Jan 5, 2026
@coveralls

coveralls commented Jan 5, 2026 •

Copy link
Copy Markdown

Coverage Status

coverage: 80.866% (-0.006%) from 80.872%
when pulling c4243b4 on mciuchitu:fix/mongodb-arrays
into 1127789 on typeorm:master.

@alumni alumni changed the title fix: process correctly embedded arrays of nested documents for MongoDB fix(mongo): correctly process embedded arrays of nested documents Jan 5, 2026

@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.

LGTM 👏
Thanks @mciuchitu

@gioboa
gioboa merged commit bfc293f into typeorm:master Jan 5, 2026
@mciuchitu
mciuchitu deleted the fix/mongodb-arrays branch January 6, 2026 12:04
Cprakhar pushed a commit to Cprakhar/typeorm that referenced this pull request Jan 7, 2026
mgohin pushed a commit to mgohin/typeorm that referenced this pull request Jan 15, 2026
kranners pushed a commit to kranners/typeorm that referenced this pull request Mar 1, 2026
@pkuczynski pkuczynski added this to the 1.0 milestone Mar 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

repository.create strips values of columns that are both arrays and embedded objects

8 participants