Skip to content

Commit 2cdbe63

Browse files
committed
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
1 parent 930bf4b commit 2cdbe63

File tree

3 files changed

+25
-2
lines changed

3 files changed

+25
-2
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "nestjs-mongo",
3-
"version": "0.14.0",
3+
"version": "0.14.1",
44
"description": "A NestJS module that provide a simple mongodb orm like",
55
"keywords": [
66
"nestjs",

src/entity/manager.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -390,7 +390,10 @@ export class EntityManager {
390390
);
391391
}
392392

393-
const id: ObjectId = obj[property];
393+
const id: ObjectId | undefined | null = obj[property];
394+
if (!(id instanceof ObjectId)) {
395+
return;
396+
}
394397
const filter: Filter<R> = {};
395398
filter._id = id;
396399
const relationship = await this.findOne<R>(relationMetadata.type, filter, options);
@@ -423,6 +426,9 @@ export class EntityManager {
423426
}
424427

425428
const value = obj[property];
429+
if (!Array.isArray(value)) {
430+
return [];
431+
}
426432
const relationshipsCursor = await this.find<R>(
427433
relationMetadata.type,
428434
{

test/relationship/relationship.spec.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,23 @@ describe('Relationship', () => {
216216
)
217217
).toHaveLength(2);
218218
});
219+
220+
it('should return undefined for single relationship', async () => {
221+
const entityRelationShip = new EntityRelationship();
222+
entityRelationShip.property = 'test_with_no_parent';
223+
224+
const notFound = await em.getRelationship(entityRelationShip, 'parent');
225+
expect(notFound).toBeUndefined();
226+
});
227+
228+
it('should return undefined for multiple children relationships', async () => {
229+
const entityRelationShip = new EntityRelationship();
230+
entityRelationShip.property = 'test_with_no_children';
231+
232+
const notFound = await em.getRelationships(entityRelationShip, 'children');
233+
expect(notFound).toBeInstanceOf(Array);
234+
expect(notFound).toHaveLength(0);
235+
});
219236
});
220237
});
221238
});

0 commit comments

Comments
 (0)