Skip to content

Conversation

@jamis
Copy link
Contributor

@jamis jamis commented Feb 5, 2025

(backport to 9.0)

In certain situations, calling #size on a HABTM association will return the wrong count.

This will happen if the association is
initialized to a single element (forcing the _unloaded Criteria object to be scoped to that specific element) and then assigning an array of multiple (already-persisted) elements to the association, where one of the elements is the same element that already existed there.

In this case, _unloaded.count will return 1, and then the _added array will have two previously-persisted records. Naive implementations will thus return either 1, or 3, rather than the correct answer of 2. To get the correct answer, it is necessary to add a filter condition to _unloaded.count that excludes the records in the _added array.

In certain situations, calling #size on a HABTM association will
return the wrong count.

This will happen if the association is
initialized to a single element (forcing the _unloaded Criteria
object to be scoped to that specific element) and then assigning
an array of multiple (already-persisted) elements to the association,
where one of the elements is the same element that already existed
there.

In this case, `_unloaded.count` will return 1, and then the
_added array will have two previously-persisted records. Naive
implementations will thus return either 1, or 3, rather than the
correct answer of 2. To get the correct answer, it is necessary
to add a filter condition to `_unloaded.count` that excludes the
records in the `_added` array.
@jamis jamis requested a review from comandeo-mongo February 5, 2025 19:42
@jamis jamis merged commit e3cbe4f into mongodb:9.0-stable Feb 18, 2025
62 of 67 checks passed
@jamis jamis deleted the 5844-habtm-count-bug-9.0 branch February 18, 2025 15:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants