From a53d2dbacafee48d1ccd4c6817c404b6ee4a3459 Mon Sep 17 00:00:00 2001 From: Alexandre BODIN Date: Thu, 11 Feb 2021 15:52:59 +0100 Subject: [PATCH] Fix mongoose autopopulate recursively looping to infinity when cycles appear (#9367) --- .../strapi-connector-mongoose/lib/mount-models.js | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/packages/strapi-connector-mongoose/lib/mount-models.js b/packages/strapi-connector-mongoose/lib/mount-models.js index 0fd55a6ef6..0b7aa7dae5 100644 --- a/packages/strapi-connector-mongoose/lib/mount-models.js +++ b/packages/strapi-connector-mongoose/lib/mount-models.js @@ -311,7 +311,9 @@ module.exports = async ({ models, target }, ctx) => { const createOnFetchPopulateFn = ({ morphAssociations, componentAttributes, definition }) => { return function() { const populatedPaths = this.getPopulatedPaths(); - const { publicationState } = this.getOptions(); + const { publicationState, _depth = 0 } = this.getOptions(); + + if (_depth > 2) return; const getMatchQuery = assoc => { const assocModel = strapi.db.getModelByAssoc(assoc); @@ -334,7 +336,10 @@ const createOnFetchPopulateFn = ({ morphAssociations, componentAttributes, defin this.populate({ path: alias, match: matchQuery, options: { publicationState } }); } else if (populatedPaths.includes(alias)) { _.set(this._mongooseOptions.populate, [alias, 'path'], `${alias}.ref`); - _.set(this._mongooseOptions.populate, [alias, 'options'], { publicationState }); + _.set(this._mongooseOptions.populate, [alias, 'options'], { + publicationState, + _depth: _depth + 1, + }); if (matchQuery !== undefined) { _.set(this._mongooseOptions.populate, [alias, 'match'], matchQuery); @@ -350,13 +355,13 @@ const createOnFetchPopulateFn = ({ morphAssociations, componentAttributes, defin this.populate({ path: ast.alias, match: getMatchQuery(ast), - options: { publicationState }, + options: { publicationState, _depth: _depth + 1 }, }); }); } componentAttributes.forEach(key => { - this.populate({ path: `${key}.ref`, options: { publicationState } }); + this.populate({ path: `${key}.ref`, options: { publicationState, _depth: _depth + 1 } }); }); }; };