Skip to content

Commit

Permalink
fix: allow to pass ObjectLiteral in mongo find where condition (#9632)
Browse files Browse the repository at this point in the history
Closes: #9518
  • Loading branch information
ayuvlasenko committed Dec 29, 2022
1 parent b97633b commit 4eda5df
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 2 deletions.
7 changes: 5 additions & 2 deletions src/find-options/mongodb/MongoFindOneOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@ import { ObjectLiteral } from "../../common/ObjectLiteral"
/**
* Defines a special criteria to find specific entity.
*/
export type MongoFindOneOptions<Entity = any> = FindOneOptions<Entity> & {
export type MongoFindOneOptions<Entity = any> = Omit<
FindOneOptions<Entity>,
"where"
> & {
/**
* Simple condition that should be applied to match entities.
*/
where?: ObjectLiteral
where?: FindOneOptions<Entity>["where"] | ObjectLiteral
}
10 changes: 10 additions & 0 deletions test/github-issues/9518/entity/Post.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { Column, Entity, ObjectID, ObjectIdColumn } from "../../../../src"

@Entity()
export class Post {
@ObjectIdColumn()
id: ObjectID

@Column()
title: string
}
46 changes: 46 additions & 0 deletions test/github-issues/9518/issue-9518.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import "reflect-metadata"
import {
createTestingConnections,
closeTestingConnections,
reloadTestingDatabases,
} from "../../utils/test-utils"
import { DataSource } from "../../../src/data-source/DataSource"
import { expect } from "chai"
import { Post } from "./entity/Post"

describe("github issues > #9518 Can't pass ObjectLiteral in MongoRepository.find where condition due to typings", () => {
let connections: DataSource[]
before(
async () =>
(connections = await createTestingConnections({
entities: [Post],
enabledDrivers: ["mongodb"],
})),
)
beforeEach(() => reloadTestingDatabases(connections))
after(() => closeTestingConnections(connections))

it("should be able to use ObjectLiteral in find where condition", () =>
Promise.all(
connections.map(async (connection) => {
const postRepository = connection.getMongoRepository(Post)

const firstPost = new Post()
firstPost.title = "Post #1"
await postRepository.save(firstPost)

const secondPost = new Post()
secondPost.title = "Post #2"
await postRepository.save(secondPost)

const loadedPosts = await postRepository.find({
where: {
title: { $in: ["Post #1"] },
},
})

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

0 comments on commit 4eda5df

Please sign in to comment.