MCPcopy Create free account
hub / github.com/Automattic/mongoose / _execPopulateQuery

Function _execPopulateQuery

lib/model.js:4742–4860  ·  view source on GitHub ↗
(mod, match, select)

Source from the content-addressed store, hash-verified

4740 */
4741
4742function _execPopulateQuery(mod, match, select) {
4743 // `null` match means `mod`'s documents have no ids to query, possible if a large populate
4744 // was split into a query per document (gh-5890). Skip executing a query: `_assign()` still
4745 // sets the documents' populated paths to the appropriate default value.
4746 if (match == null) {
4747 return Promise.resolve({ docs: [], deferredPopulates: [] });
4748 }
4749 let subPopulate = clone(mod.options.populate);
4750 const queryOptions = {};
4751 if (mod.options.skip !== undefined) {
4752 queryOptions.skip = mod.options.skip;
4753 }
4754 if (mod.options.limit !== undefined) {
4755 queryOptions.limit = mod.options.limit;
4756 }
4757 if (mod.options.perDocumentLimit !== undefined) {
4758 queryOptions.perDocumentLimit = mod.options.perDocumentLimit;
4759 }
4760 Object.assign(queryOptions, mod.options.options);
4761
4762 if (mod.count) {
4763 delete queryOptions.skip;
4764 }
4765
4766 if (queryOptions.perDocumentLimit != null) {
4767 queryOptions.limit = queryOptions.perDocumentLimit;
4768 delete queryOptions.perDocumentLimit;
4769 } else if (queryOptions.limit != null) {
4770 queryOptions.limit = queryOptions.limit * mod.ids.length;
4771 }
4772
4773 // When there's a per-document match function, defer any populate (including from hooks)
4774 // until after sift filtering, otherwise sift compares ObjectIds against populated docs.
4775 if (Array.isArray(mod.match)) {
4776 queryOptions._deferPopulate = true;
4777 }
4778
4779 const query = mod.model.find(match, select, queryOptions);
4780 // If we're doing virtual populate and projection is inclusive and foreign
4781 // field is not selected, automatically select it because mongoose needs it.
4782 // If projection is exclusive and client explicitly unselected the foreign
4783 // field, that's the client's fault.
4784 for (const foreignField of mod.foreignField) {
4785 if (foreignField !== '_id' &&
4786 query.selectedInclusively() &&
4787 !isPathSelectedInclusive(query._fields, foreignField)) {
4788 query.select(foreignField);
4789 }
4790 }
4791
4792 // If using count, still need the `foreignField` so we can match counts
4793 // to documents, otherwise we would need a separate `count()` for every doc.
4794 if (mod.count) {
4795 for (const foreignField of mod.foreignField) {
4796 query.select(foreignField);
4797 }
4798 }
4799

Callers

nothing calls this directly

Calls 4

populateMethod · 0.80
findMethod · 0.65
cloneFunction · 0.50
setMethod · 0.45

Tested by

no test coverage detected