From 2cdbe63e59514e7d66f3d0a20b893ba1ae65e82c Mon Sep 17 00:00:00 2001 From: Rmannn Date: Wed, 4 May 2022 21:20:52 +0200 Subject: [PATCH] fix: getRelationship - getRelationship now returns undefined if the base property is not an ObjectId - getRelationships return empty array if base property is not an array --- package.json | 2 +- src/entity/manager.ts | 8 +++++++- test/relationship/relationship.spec.ts | 17 +++++++++++++++++ 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index dfa4d8bf..d027f07a 100755 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "nestjs-mongo", - "version": "0.14.0", + "version": "0.14.1", "description": "A NestJS module that provide a simple mongodb orm like", "keywords": [ "nestjs", diff --git a/src/entity/manager.ts b/src/entity/manager.ts index 17d22162..e1424fb9 100644 --- a/src/entity/manager.ts +++ b/src/entity/manager.ts @@ -390,7 +390,10 @@ export class EntityManager { ); } - const id: ObjectId = obj[property]; + const id: ObjectId | undefined | null = obj[property]; + if (!(id instanceof ObjectId)) { + return; + } const filter: Filter = {}; filter._id = id; const relationship = await this.findOne(relationMetadata.type, filter, options); @@ -423,6 +426,9 @@ export class EntityManager { } const value = obj[property]; + if (!Array.isArray(value)) { + return []; + } const relationshipsCursor = await this.find( relationMetadata.type, { diff --git a/test/relationship/relationship.spec.ts b/test/relationship/relationship.spec.ts index 37f463ca..5b7e6025 100644 --- a/test/relationship/relationship.spec.ts +++ b/test/relationship/relationship.spec.ts @@ -216,6 +216,23 @@ describe('Relationship', () => { ) ).toHaveLength(2); }); + + it('should return undefined for single relationship', async () => { + const entityRelationShip = new EntityRelationship(); + entityRelationShip.property = 'test_with_no_parent'; + + const notFound = await em.getRelationship(entityRelationShip, 'parent'); + expect(notFound).toBeUndefined(); + }); + + it('should return undefined for multiple children relationships', async () => { + const entityRelationShip = new EntityRelationship(); + entityRelationShip.property = 'test_with_no_children'; + + const notFound = await em.getRelationships(entityRelationShip, 'children'); + expect(notFound).toBeInstanceOf(Array); + expect(notFound).toHaveLength(0); + }); }); }); });