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

Function _execPopulateQuery

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

Source from the content-addressed store, hash-verified

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

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