Skip to content

Conversation

@CHOIJEWON
Copy link
Contributor

Description of change

Fixes #10264

The findBy() method was missing in MongoEntityManager, causing it to inherit the SQL-based implementation from EntityManager
which uses QueryBuilder. Since MongoDB does not support QueryBuilder, this resulted in a "Query Builder is not supported by MongoDB" error.

The Problem

When calling repository.findBy() on a MongoDB repository:

const users = await mongoRepository.findBy({ firstName: "John" });
// ❌ TypeORMError: Query Builder is not supported by MongoDB.

Call chain:
MongoRepository.findBy()
   EntityManager.findBy()  // No override in MongoEntityManager
     createQueryBuilder()  // SQL-based, not supported in MongoDB
        Error thrown

The Solution

Override findBy() in MongoEntityManager to use MongoDB's native cursor API instead of QueryBuilder:

  async findBy<Entity>(
      entityClassOrName: EntityTarget<Entity>,
      where: any,
  ): Promise<Entity[]> {
      return this.executeFind(entityClassOrName, where)
  }

This follows the same pattern as existing methods like findAndCountBy() and findOneBy(), which already work correctly.

Changes:

  • ✅ Added findBy() method to MongoEntityManager (uses MongoDB cursor API)
  • ✅ Added comprehensive test case in mongo-repository.test.ts

Testing

All MongoDB tests pass successfully:

npm run test:fast -- --grep "mongodb"
# 47 passing

Specific test for this fix:

npm run test:fast -- --grep "should be able to use findBy method"
# ✔ should be able to use findBy method

Backward Compatibility

✅ No breaking changes

  • Existing code continues to work
  • Only adds missing functionality that was throwing errors
  • Follows existing patterns in MongoEntityManager

Related Methods

Note: These methods already work correctly and did not need changes:

  • findOneBy() - Already implemented in MongoEntityManager
  • findAndCountBy() - Already implemented in MongoEntityManager
  • findOneByOrFail() - Works via inheritance (calls findOneBy())

Pull-Request Checklist

  • Code is up-to-date with the master branch
  • This pull request links relevant issues as Fixes #00000
  • There are new or updated tests validating the change (tests/**.test.ts)
  • Documentation has been updated to reflect this change (docs/docs/**.md)

Additional Notes

The fix is minimal and follows the established patterns in the codebase. Please let me know if any adjustments are needed!

…m#10264)

The findBy() method was missing in MongoEntityManager, causing it to
inherit the SQL-based implementation from EntityManager which uses
QueryBuilder. Since MongoDB does not support QueryBuilder, this resulted
in a Query Builder is not supported by MongoDB error.

This fix adds the findBy() method override to use MongoDB's native
cursor API instead, following the same pattern as existing methods like
findAndCountBy() and findOneBy().

Changes:
- Add findBy() method to MongoEntityManager
- Add test case in mongo-repository.test.ts
- Remove incorrectly placed mongo-query-builder test directory

Fixes typeorm#10264
@qodo-free-for-open-source-projects

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

⏱️ Estimated effort to review: 2 🔵🔵⚪⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Import Organization

The imports from mongodb/typings have been reorganized alphabetically. While this improves readability, verify that all previously imported types are still present and no functionality is accidentally broken due to missing imports in other parts of the codebase that might depend on re-exports.

import {
    AggregateOptions,
    AggregationCursor,
    AnyBulkWriteOperation,
    BulkWriteOptions,
    BulkWriteResult,
    ChangeStream,
    ChangeStreamOptions,
    Collection,
    CollStats,
    CollStatsOptions,
    CommandOperationOptions,
    CountDocumentsOptions,
    CountOptions,
    CreateIndexesOptions,
    DeleteOptions,
    DeleteResult as DeleteResultMongoDb,
    Document,
    Filter,
    FilterOperators,
    FindCursor,
    FindOneAndDeleteOptions,
    FindOneAndReplaceOptions,
    FindOneAndUpdateOptions,
    IndexDescription,
    IndexInformationOptions,
    IndexSpecification,
    InsertManyResult,
    InsertOneOptions,
    InsertOneResult,
    ListIndexesCursor,
    ListIndexesOptions,
    ObjectId,
    OptionalId,
    OrderedBulkOperation,
    RenameOptions,
    ReplaceOptions,
    UnorderedBulkOperation,
    UpdateFilter,
    UpdateOptions,
    UpdateResult as UpdateResultMongoDb,
} from "../driver/mongodb/typings"
Test Coverage

The test only validates the happy path with simple equality conditions. Consider adding test cases for edge cases such as empty results, complex query conditions with multiple fields, or MongoDB-specific operators to ensure the findBy method handles various scenarios correctly.

it("should be able to use findBy method", () =>
    Promise.all(
        connections.map(async (connection) => {
            const postRepository = connection.getMongoRepository(Post)

            // save few posts
            const firstPost = new Post()
            firstPost.title = "Post #1"
            firstPost.text = "Everything about post #1"
            await postRepository.save(firstPost)

            const secondPost = new Post()
            secondPost.title = "Post #1"
            secondPost.text = "Everything about post #2"
            await postRepository.save(secondPost)

            const thirdPost = new Post()
            thirdPost.title = "Post #2"
            thirdPost.text = "Everything about post #3"
            await postRepository.save(thirdPost)

            const loadedPosts = await postRepository.findBy({
                title: "Post #1",
            })

            expect(loadedPosts).to.have.length(2)
            expect(loadedPosts[0]).to.be.instanceOf(Post)
            expect(loadedPosts[1]).to.be.instanceOf(Post)
            expect(loadedPosts[0].title).to.eql("Post #1")
            expect(loadedPosts[1].title).to.eql("Post #1")
        }),
    ))

@CHOIJEWON CHOIJEWON changed the title fix(mongodb): add missing findBy method to MongoEntityManager (#10264) fix: add missing findBy method to MongoEntityManager Dec 2, 2025
@pkg-pr-new
Copy link

pkg-pr-new bot commented Dec 2, 2025

commit: c3d7fbf

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

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
General
Improve type safety for method

Improve type safety in the new findBy method by changing the where parameter's
type from any to the more specific Filter.

src/entity-manager/MongoEntityManager.ts [167-172]

 async findBy<Entity>(
     entityClassOrName: EntityTarget<Entity>,
-    where: any,
+    where: Filter<Entity>,
 ): Promise<Entity[]> {
     return this.executeFind(entityClassOrName, where)
 }
  • Apply / Chat
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly proposes changing the where parameter's type from any to Filter<Entity>, which improves type safety and developer experience for the newly added findBy method.

Low
  • More

@coveralls
Copy link

Coverage Status

coverage: 80.773% (-0.008%) from 80.781%
when pulling c3d7fbf on CHOIJEWON:fix/mongodb-findBy
into ec3ea10 on typeorm:master.

Copy link
Collaborator

@gioboa gioboa left a comment

Choose a reason for hiding this comment

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

Thanks for your help @CHOIJEWON
It looks awesome to me 👏

@gioboa gioboa requested review from alumni and pkuczynski December 2, 2025 07:16
@alumni alumni merged commit 38715bb into typeorm:master Dec 2, 2025
64 checks passed
@CHOIJEWON CHOIJEWON deleted the fix/mongodb-findBy branch December 3, 2025 02:42
mgohin pushed a commit to mgohin/typeorm that referenced this pull request Jan 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

MongoDB driver findBy() method uses unsupported Query Builder

4 participants