Skip to content

Commit

Permalink
fix: allow for string id in mongo.findByIds call (#7838)
Browse files Browse the repository at this point in the history
  • Loading branch information
imnotjames committed Jul 10, 2021
1 parent b8239d0 commit 4b45ae1
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
17 changes: 14 additions & 3 deletions src/entity-manager/MongoEntityManager.ts
Expand Up @@ -133,10 +133,21 @@ export class MongoEntityManager extends EntityManager {
const objectIdInstance = PlatformTools.load("mongodb").ObjectID;
query["_id"] = {
$in: ids.map(id => {
if (id instanceof objectIdInstance)
return id;
if (typeof id === "string") {
return new objectIdInstance(id);
}

return id[metadata.objectIdColumn!.propertyName];
if (typeof id === "object") {
if (id instanceof objectIdInstance) {
return id;
}

const propertyName = metadata.objectIdColumn!.propertyName;

if (id[propertyName] instanceof objectIdInstance) {
return id[propertyName];
}
}
})
};

Expand Down
20 changes: 20 additions & 0 deletions test/functional/mongodb/basic/mongo-repository/mongo-repository.ts
Expand Up @@ -86,6 +86,26 @@ describe("mongodb > MongoRepository", () => {
loadedPosts[0].text.should.be.equal("Everything about post #1");

})));

it("should be able to use findByIds with both objectId and strings", () => 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 #2";
secondPost.text = "Everything about post #2";
await postRepository.save(secondPost);

expect(await postRepository.findByIds([ firstPost.id ])).to.have.length(1);
expect(await postRepository.findByIds([ firstPost.id.toHexString() ])).to.have.length(1);
expect(await postRepository.findByIds([ { id: firstPost.id } ])).to.have.length(1);
expect(await postRepository.findByIds([ undefined ])).to.have.length(0);
})));

// todo: cover other methods as well
it("should be able to save and update mongo entities", () => Promise.all(connections.map(async connection => {
Expand Down

0 comments on commit 4b45ae1

Please sign in to comment.