| 4807 | */ |
| 4808 | |
| 4809 | function _execPopulateQuery(mod, match, select) { |
| 4810 | // `null` match means `mod`'s documents have no ids to query, possible if a large populate |
| 4811 | // was split into a query per document (gh-5890). Skip executing a query: `_assign()` still |
| 4812 | // sets the documents' populated paths to the appropriate default value. |
| 4813 | if (match == null) { |
| 4814 | return Promise.resolve({ docs: [], deferredPopulates: [] }); |
| 4815 | } |
| 4816 | let subPopulate = clone(mod.options.populate); |
| 4817 | const queryOptions = {}; |
| 4818 | if (mod.options.skip !== undefined) { |
| 4819 | queryOptions.skip = mod.options.skip; |
| 4820 | } |
| 4821 | if (mod.options.limit !== undefined) { |
| 4822 | queryOptions.limit = mod.options.limit; |
| 4823 | } |
| 4824 | if (mod.options.perDocumentLimit !== undefined) { |
| 4825 | queryOptions.perDocumentLimit = mod.options.perDocumentLimit; |
| 4826 | } |
| 4827 | Object.assign(queryOptions, mod.options.options); |
| 4828 | // Inherit the parent query's read settings unless populate options set them, see `setInheritedReadOptions()` |
| 4829 | if (queryOptions.readPreference == null && mod.options._inheritedReadPreference != null) { |
| 4830 | queryOptions.readPreference = mod.options._inheritedReadPreference; |
| 4831 | } |
| 4832 | if (queryOptions.readConcern == null && mod.options._inheritedReadConcern != null) { |
| 4833 | queryOptions.readConcern = mod.options._inheritedReadConcern; |
| 4834 | } |
| 4835 | |
| 4836 | if (mod.count) { |
| 4837 | delete queryOptions.skip; |
| 4838 | } |
| 4839 | |
| 4840 | if (queryOptions.perDocumentLimit != null) { |
| 4841 | queryOptions.limit = queryOptions.perDocumentLimit; |
| 4842 | delete queryOptions.perDocumentLimit; |
| 4843 | } else if (queryOptions.limit != null) { |
| 4844 | queryOptions.limit = queryOptions.limit * mod.ids.length; |
| 4845 | } |
| 4846 | |
| 4847 | // When there's a per-document match function, defer any populate (including from hooks) |
| 4848 | // until after sift filtering, otherwise sift compares ObjectIds against populated docs. |
| 4849 | if (Array.isArray(mod.match)) { |
| 4850 | queryOptions._deferPopulate = true; |
| 4851 | } |
| 4852 | |
| 4853 | const query = mod.model.find(match, select, queryOptions); |
| 4854 | // If we're doing virtual populate and projection is inclusive and foreign |
| 4855 | // field is not selected, automatically select it because mongoose needs it. |
| 4856 | // If projection is exclusive and client explicitly unselected the foreign |
| 4857 | // field, that's the client's fault. |
| 4858 | for (const foreignField of mod.foreignField) { |
| 4859 | if (foreignField !== '_id' && |
| 4860 | query.selectedInclusively() && |
| 4861 | !isPathSelectedInclusive(query._fields, foreignField)) { |
| 4862 | query.select(foreignField); |
| 4863 | } |
| 4864 | } |
| 4865 | |
| 4866 | // If using count, still need the `foreignField` so we can match counts |