From 0cc0c820cf068496105b2506d0928b83e65516ea Mon Sep 17 00:00:00 2001 From: Marc-Antoine Fernandes Date: Mon, 13 Apr 2020 16:26:45 +0200 Subject: [PATCH] Handle nested field populate --- packages/moleculer-db/package-lock.json | 2 +- packages/moleculer-db/src/index.js | 8 +++--- packages/moleculer-db/test/unit/index.spec.js | 27 +++++++++++++++++++ 3 files changed, 32 insertions(+), 5 deletions(-) diff --git a/packages/moleculer-db/package-lock.json b/packages/moleculer-db/package-lock.json index 47d11a06..e73a21d7 100644 --- a/packages/moleculer-db/package-lock.json +++ b/packages/moleculer-db/package-lock.json @@ -1,6 +1,6 @@ { "name": "moleculer-db", - "version": "0.8.6", + "version": "0.8.7", "lockfileVersion": 1, "requires": true, "dependencies": { diff --git a/packages/moleculer-db/src/index.js b/packages/moleculer-db/src/index.js index b8ac258a..dfd7a7af 100644 --- a/packages/moleculer-db/src/index.js +++ b/packages/moleculer-db/src/index.js @@ -619,16 +619,16 @@ module.exports = { let arr = Array.isArray(docs) ? docs : [docs]; // Collect IDs from field of docs (flatten, compact & unique list) - let idList = _.uniq(_.flattenDeep(_.compact(arr.map(doc => doc[field])))); + let idList = _.uniq(_.flattenDeep(_.compact(arr.map(doc => _.get(doc, field))))); // Replace the received models according to IDs in the original docs const resultTransform = (populatedDocs) => { arr.forEach(doc => { - let id = doc[field]; + let id = _.get(doc, field); if (_.isArray(id)) { let models = _.compact(id.map(id => populatedDocs[id])); - doc[field] = models; + _.set(doc, field, models); } else { - doc[field] = populatedDocs[id]; + _.set(doc, field, populatedDocs[id]); } }); }; diff --git a/packages/moleculer-db/test/unit/index.spec.js b/packages/moleculer-db/test/unit/index.spec.js index 48f8484f..09951426 100644 --- a/packages/moleculer-db/test/unit/index.spec.js +++ b/packages/moleculer-db/test/unit/index.spec.js @@ -679,6 +679,7 @@ describe("Test populateDocs method", () => { adapter: mockAdapter, settings: { populates: { + "likes.users": "users.get", "comments": "comments.get", "author": { action: "users.get", @@ -826,6 +827,32 @@ describe("Test populateDocs method", () => { }).catch(protectReject); }); + it("should call 'populateDocs' with single doc & only likes.users population", () => { + const ctx = { params: {} }; + ctx.call = jest.fn(() => Promise.resolve({ + "3": { + "name": "Walter" + }, + "5": { + "name": "John" + }, + "8": { + "name": "Jane" + } + })); + const doc = { id: 4, likes: { users: [8, 3], shared: 4 } }; + + return service.populateDocs(ctx, doc, ["likes.users"]).then(res => { + expect(res).toEqual({ + id: 4, + likes: { + users: [{ name: "Jane" }, { name: "Walter" }], + shared: 4, + }, + }); + }).catch(protectReject); + }); + it("should return docs if no populate list", () => { const docs = []; const ctx = { params: {} };