Commit fa8419e
fix(db-mongodb): remove duplicate IDs in nested relationship queries (#16354)
### What?
When querying through a nested relationship (e.g. `where: {
'movie.name': { equals: '...' } }`), the `$in` array used to filter
parent collection documents was populated with duplicate entries — each
document ID was pushed twice: once as a string and once as a
`Types.ObjectId`.
### Why?
In `buildSearchParams.ts`, the `else` branch (for non-`join` fields) was
doing:
**Before:**
```ts
const stringID = doc._id.toString()
$in.push(stringID)
if (Types.ObjectId.isValid(stringID)) {
$in.push(doc._id)
}
```
Mongoose auto-casts 24-hex strings to ObjectId before sending queries to MongoDB, so both entries resolve to the same ObjectId. This caused every ID to appear twice in the $in array (e.g. 100 IDs → 200 entries), resulting in significantly larger queries, slower plaremnning times, and in extreme cases client disconnects due to timeouts.
How?
After:
```ts
$in.push(doc._id)
```
The _id returned by Mongoose's .lean() is already the correct BSON type — ObjectId for standard collections, string/number for custom ID collections — so no extra casting is needed.
A regression test was added to test/relationships/int.spec.ts that queries directors through a nested movie relationship using or conditions and asserts no duplicate documents are returned.
---------
Co-authored-by: Sasha Rakhmatulin <sasha@ritsuko.dev>1 parent b3b8198 commit fa8419e
2 files changed
Lines changed: 33 additions & 2 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
217 | 217 | | |
218 | 218 | | |
219 | 219 | | |
220 | | - | |
221 | | - | |
222 | 220 | | |
223 | 221 | | |
| 222 | + | |
| 223 | + | |
224 | 224 | | |
225 | 225 | | |
226 | 226 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
473 | 473 | | |
474 | 474 | | |
475 | 475 | | |
| 476 | + | |
| 477 | + | |
| 478 | + | |
| 479 | + | |
| 480 | + | |
| 481 | + | |
| 482 | + | |
| 483 | + | |
| 484 | + | |
| 485 | + | |
| 486 | + | |
| 487 | + | |
| 488 | + | |
| 489 | + | |
| 490 | + | |
| 491 | + | |
| 492 | + | |
| 493 | + | |
| 494 | + | |
| 495 | + | |
| 496 | + | |
| 497 | + | |
| 498 | + | |
| 499 | + | |
| 500 | + | |
| 501 | + | |
| 502 | + | |
| 503 | + | |
| 504 | + | |
| 505 | + | |
| 506 | + | |
476 | 507 | | |
477 | 508 | | |
478 | 509 | | |
| |||
0 commit comments