diff --git a/packages/core/database/src/__tests__/field-options/sort-by.test.ts b/packages/core/database/src/__tests__/field-options/sort-by.test.ts index e9f194606..62ed4a724 100644 --- a/packages/core/database/src/__tests__/field-options/sort-by.test.ts +++ b/packages/core/database/src/__tests__/field-options/sort-by.test.ts @@ -151,10 +151,11 @@ describe('associated field order', () => { }); const u1 = await db.getRepository('users').findOne({ - appends: ['posts.tags'], + appends: ['posts.tags', 'posts.title'], }); const u1Json = u1.toJSON(); + const u1Posts = u1Json['posts']; expect(u1Posts.map((p) => p['title'])).toEqual(['a', 'b', 'c']); diff --git a/packages/core/database/src/__tests__/repository/find.test.ts b/packages/core/database/src/__tests__/repository/find.test.ts index 7f5520f94..e3732fe02 100644 --- a/packages/core/database/src/__tests__/repository/find.test.ts +++ b/packages/core/database/src/__tests__/repository/find.test.ts @@ -488,6 +488,17 @@ describe('repository find', () => { expect(user['posts']).toBeDefined(); }); + test('find with nested fields', async () => { + const user = await User.repository.findOne({ + fields: ['posts.comments.content'], + }); + + const userData = user.toJSON(); + + const post = userData['posts'][0]; + expect(Object.keys(post)).toEqual(['comments']); + }); + describe('find with appends', () => { test('toJSON', async () => { const user = await User.repository.findOne({ diff --git a/packages/core/database/src/eager-loading/eager-loading-tree.ts b/packages/core/database/src/eager-loading/eager-loading-tree.ts index 72d0e7aeb..4d7203fb9 100644 --- a/packages/core/database/src/eager-loading/eager-loading-tree.ts +++ b/packages/core/database/src/eager-loading/eager-loading-tree.ts @@ -343,7 +343,8 @@ export class EagerLoadingTree { }); } - const nodeRawAttributes = node.rawAttributes; + // if no attributes are specified, return empty fields + const nodeRawAttributes = node.rawAttributes || []; if (!lodash.isArray(nodeRawAttributes)) { return; diff --git a/packages/core/server/src/middlewares/data-template.ts b/packages/core/server/src/middlewares/data-template.ts index 02909bf7f..a2a625f4c 100644 --- a/packages/core/server/src/middlewares/data-template.ts +++ b/packages/core/server/src/middlewares/data-template.ts @@ -37,7 +37,7 @@ const traverseBelongsToMany = (arr: any[], { collection, exclude = [], through } const throughCollection = collection.db.getCollection(through); return arr.map((item) => { const data = traverseJSON(item[through], { collection: throughCollection, exclude }); - if (Object.keys(data).length) { + if (data && Object.keys(data).length) { item[through] = data; } else { delete item[through];