getModelsMapForPopulate.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. 'use strict';
  2. const MongooseError = require('../../error/index');
  3. const SkipPopulateValue = require('./SkipPopulateValue');
  4. const get = require('../get');
  5. const getDiscriminatorByValue = require('../discriminator/getDiscriminatorByValue');
  6. const isPathExcluded = require('../projection/isPathExcluded');
  7. const getSchemaTypes = require('./getSchemaTypes');
  8. const getVirtual = require('./getVirtual');
  9. const lookupLocalFields = require('./lookupLocalFields');
  10. const mpath = require('mpath');
  11. const normalizeRefPath = require('./normalizeRefPath');
  12. const util = require('util');
  13. const utils = require('../../utils');
  14. const modelSymbol = require('../symbols').modelSymbol;
  15. const populateModelSymbol = require('../symbols').populateModelSymbol;
  16. const schemaMixedSymbol = require('../../schema/symbols').schemaMixedSymbol;
  17. module.exports = function getModelsMapForPopulate(model, docs, options) {
  18. let i;
  19. let doc;
  20. const len = docs.length;
  21. const available = {};
  22. const map = [];
  23. const modelNameFromQuery = options.model && options.model.modelName || options.model;
  24. let schema;
  25. let refPath;
  26. let Model;
  27. let currentOptions;
  28. let modelNames;
  29. let modelName;
  30. const originalModel = options.model;
  31. let isVirtual = false;
  32. const modelSchema = model.schema;
  33. let allSchemaTypes = getSchemaTypes(modelSchema, null, options.path);
  34. allSchemaTypes = Array.isArray(allSchemaTypes) ? allSchemaTypes : [allSchemaTypes].filter(v => v != null);
  35. const _firstWithRefPath = allSchemaTypes.find(schematype => get(schematype, 'options.refPath', null) != null);
  36. for (i = 0; i < len; i++) {
  37. doc = docs[i];
  38. let justOne = null;
  39. schema = getSchemaTypes(modelSchema, doc, options.path);
  40. // Special case: populating a path that's a DocumentArray unless
  41. // there's an explicit `ref` or `refPath` re: gh-8946
  42. if (schema != null &&
  43. schema.$isMongooseDocumentArray &&
  44. schema.options.ref == null &&
  45. schema.options.refPath == null) {
  46. continue;
  47. }
  48. // Populating a nested path should always be a no-op re: #9073.
  49. // People shouldn't do this, but apparently they do.
  50. if (modelSchema.nested[options.path]) {
  51. continue;
  52. }
  53. const isUnderneathDocArray = schema && schema.$isUnderneathDocArray;
  54. if (isUnderneathDocArray && get(options, 'options.sort') != null) {
  55. return new MongooseError('Cannot populate with `sort` on path ' + options.path +
  56. ' because it is a subproperty of a document array');
  57. }
  58. modelNames = null;
  59. let isRefPath = !!_firstWithRefPath;
  60. let normalizedRefPath = _firstWithRefPath ? get(_firstWithRefPath, 'options.refPath', null) : null;
  61. let schemaOptions = null;
  62. if (Array.isArray(schema)) {
  63. const schemasArray = schema;
  64. for (const _schema of schemasArray) {
  65. let _modelNames;
  66. let res;
  67. try {
  68. res = _getModelNames(doc, _schema);
  69. _modelNames = res.modelNames;
  70. isRefPath = isRefPath || res.isRefPath;
  71. normalizedRefPath = normalizeRefPath(normalizedRefPath, doc, options.path) ||
  72. res.refPath;
  73. justOne = res.justOne;
  74. } catch (error) {
  75. return error;
  76. }
  77. if (isRefPath && !res.isRefPath) {
  78. continue;
  79. }
  80. if (!_modelNames) {
  81. continue;
  82. }
  83. modelNames = modelNames || [];
  84. for (const modelName of _modelNames) {
  85. if (modelNames.indexOf(modelName) === -1) {
  86. modelNames.push(modelName);
  87. }
  88. }
  89. }
  90. } else {
  91. try {
  92. const res = _getModelNames(doc, schema);
  93. modelNames = res.modelNames;
  94. isRefPath = res.isRefPath;
  95. normalizedRefPath = res.refPath;
  96. justOne = res.justOne;
  97. schemaOptions = get(schema, 'options.populate', null);
  98. } catch (error) {
  99. return error;
  100. }
  101. if (!modelNames) {
  102. continue;
  103. }
  104. }
  105. const _virtualRes = getVirtual(model.schema, options.path);
  106. const virtual = _virtualRes == null ? null : _virtualRes.virtual;
  107. let localField;
  108. let count = false;
  109. if (virtual && virtual.options) {
  110. const virtualPrefix = _virtualRes.nestedSchemaPath ?
  111. _virtualRes.nestedSchemaPath + '.' : '';
  112. if (typeof virtual.options.localField === 'function') {
  113. localField = virtualPrefix + virtual.options.localField.call(doc, doc);
  114. } else if (Array.isArray(virtual.options.localField)) {
  115. localField = virtual.options.localField.map(field => virtualPrefix + field);
  116. } else {
  117. localField = virtualPrefix + virtual.options.localField;
  118. }
  119. count = virtual.options.count;
  120. if (virtual.options.skip != null && !options.hasOwnProperty('skip')) {
  121. options.skip = virtual.options.skip;
  122. }
  123. if (virtual.options.limit != null && !options.hasOwnProperty('limit')) {
  124. options.limit = virtual.options.limit;
  125. }
  126. if (virtual.options.perDocumentLimit != null && !options.hasOwnProperty('perDocumentLimit')) {
  127. options.perDocumentLimit = virtual.options.perDocumentLimit;
  128. }
  129. } else {
  130. localField = options.path;
  131. }
  132. let foreignField = virtual && virtual.options ?
  133. virtual.options.foreignField :
  134. '_id';
  135. // `justOne = null` means we don't know from the schema whether the end
  136. // result should be an array or a single doc. This can result from
  137. // populating a POJO using `Model.populate()`
  138. if ('justOne' in options && options.justOne !== void 0) {
  139. justOne = options.justOne;
  140. } else if (virtual && virtual.options && virtual.options.refPath) {
  141. const normalizedRefPath =
  142. normalizeRefPath(virtual.options.refPath, doc, options.path);
  143. justOne = !!virtual.options.justOne;
  144. isVirtual = true;
  145. const refValue = utils.getValue(normalizedRefPath, doc);
  146. modelNames = Array.isArray(refValue) ? refValue : [refValue];
  147. } else if (virtual && virtual.options && virtual.options.ref) {
  148. let normalizedRef;
  149. if (typeof virtual.options.ref === 'function') {
  150. normalizedRef = virtual.options.ref.call(doc, doc);
  151. } else {
  152. normalizedRef = virtual.options.ref;
  153. }
  154. justOne = !!virtual.options.justOne;
  155. isVirtual = true;
  156. if (!modelNames) {
  157. modelNames = [].concat(normalizedRef);
  158. }
  159. } else if (schema && !schema[schemaMixedSymbol]) {
  160. // Skip Mixed types because we explicitly don't do casting on those.
  161. if (options.path.endsWith('.' + schema.path)) {
  162. justOne = Array.isArray(schema) ?
  163. schema.every(schema => !schema.$isMongooseArray) :
  164. !schema.$isMongooseArray;
  165. }
  166. }
  167. if (!modelNames) {
  168. continue;
  169. }
  170. if (virtual && (!localField || !foreignField)) {
  171. return new MongooseError('If you are populating a virtual, you must set the ' +
  172. 'localField and foreignField options');
  173. }
  174. options.isVirtual = isVirtual;
  175. options.virtual = virtual;
  176. if (typeof localField === 'function') {
  177. localField = localField.call(doc, doc);
  178. }
  179. if (typeof foreignField === 'function') {
  180. foreignField = foreignField.call(doc);
  181. }
  182. let match = get(options, 'match', null) ||
  183. get(currentOptions, 'match', null) ||
  184. get(options, 'virtual.options.match', null) ||
  185. get(options, 'virtual.options.options.match', null);
  186. let hasMatchFunction = typeof match === 'function';
  187. if (hasMatchFunction) {
  188. match = match.call(doc, doc);
  189. }
  190. if (Array.isArray(localField) && Array.isArray(foreignField) && localField.length === foreignField.length) {
  191. match = Object.assign({}, match);
  192. for (let i = 1; i < localField.length; ++i) {
  193. match[foreignField[i]] = convertTo_id(mpath.get(localField[i], doc, lookupLocalFields), schema);
  194. hasMatchFunction = true;
  195. }
  196. localField = localField[0];
  197. foreignField = foreignField[0];
  198. }
  199. const localFieldPathType = modelSchema._getPathType(localField);
  200. const localFieldPath = localFieldPathType === 'real' ? modelSchema.path(localField) : localFieldPathType.schema;
  201. const localFieldGetters = localFieldPath && localFieldPath.getters ? localFieldPath.getters : [];
  202. let ret;
  203. const _populateOptions = get(options, 'options', {});
  204. const getters = 'getters' in _populateOptions ?
  205. _populateOptions.getters :
  206. options.isVirtual && get(virtual, 'options.getters', false);
  207. if (localFieldGetters.length > 0 && getters) {
  208. const hydratedDoc = (doc.$__ != null) ? doc : model.hydrate(doc);
  209. const localFieldValue = mpath.get(localField, doc, lookupLocalFields);
  210. if (Array.isArray(localFieldValue)) {
  211. const localFieldHydratedValue = mpath.get(localField.split('.').slice(0, -1), hydratedDoc, lookupLocalFields);
  212. ret = localFieldValue.map((localFieldArrVal, localFieldArrIndex) =>
  213. localFieldPath.applyGetters(localFieldArrVal, localFieldHydratedValue[localFieldArrIndex]));
  214. } else {
  215. ret = localFieldPath.applyGetters(localFieldValue, hydratedDoc);
  216. }
  217. } else {
  218. ret = convertTo_id(mpath.get(localField, doc, lookupLocalFields), schema);
  219. }
  220. const id = String(utils.getValue(foreignField, doc));
  221. options._docs[id] = Array.isArray(ret) ? ret.slice() : ret;
  222. // Re: gh-8452. Embedded discriminators may not have `refPath`, so clear
  223. // out embedded discriminator docs that don't have a `refPath` on the
  224. // populated path.
  225. if (isRefPath && normalizedRefPath != null) {
  226. const pieces = normalizedRefPath.split('.');
  227. let cur = '';
  228. for (let j = 0; j < pieces.length; ++j) {
  229. const piece = pieces[j];
  230. cur = cur + (cur.length === 0 ? '' : '.') + piece;
  231. const schematype = modelSchema.path(cur);
  232. if (schematype != null &&
  233. schematype.$isMongooseArray &&
  234. schematype.caster.discriminators != null &&
  235. Object.keys(schematype.caster.discriminators).length > 0) {
  236. const subdocs = utils.getValue(cur, doc);
  237. const remnant = options.path.substr(cur.length + 1);
  238. const discriminatorKey = schematype.caster.schema.options.discriminatorKey;
  239. modelNames = [];
  240. for (const subdoc of subdocs) {
  241. const discriminatorName = utils.getValue(discriminatorKey, subdoc);
  242. const discriminator = schematype.caster.discriminators[discriminatorName];
  243. const discriminatorSchema = discriminator && discriminator.schema;
  244. if (discriminatorSchema == null) {
  245. continue;
  246. }
  247. const _path = discriminatorSchema.path(remnant);
  248. if (_path == null || _path.options.refPath == null) {
  249. const docValue = utils.getValue(localField.substr(cur.length + 1), subdoc);
  250. ret = ret.map(v => v === docValue ? SkipPopulateValue(v) : v);
  251. continue;
  252. }
  253. const modelName = utils.getValue(pieces.slice(j + 1).join('.'), subdoc);
  254. modelNames.push(modelName);
  255. }
  256. }
  257. }
  258. }
  259. let k = modelNames.length;
  260. while (k--) {
  261. modelName = modelNames[k];
  262. if (modelName == null) {
  263. continue;
  264. }
  265. // `PopulateOptions#connection`: if the model is passed as a string, the
  266. // connection matters because different connections have different models.
  267. const connection = options.connection != null ? options.connection : model.db;
  268. try {
  269. Model = originalModel && originalModel[modelSymbol] ?
  270. originalModel :
  271. modelName[modelSymbol] ? modelName : connection.model(modelName);
  272. } catch (error) {
  273. // If `ret` is undefined, we'll add an empty entry to modelsMap. We shouldn't
  274. // execute a query, but it is necessary to make sure `justOne` gets handled
  275. // correctly for setting an empty array (see gh-8455)
  276. if (ret !== undefined) {
  277. return error;
  278. }
  279. }
  280. let ids = ret;
  281. const flat = Array.isArray(ret) ? utils.array.flatten(ret) : [];
  282. if (isRefPath && Array.isArray(ret) && flat.length === modelNames.length) {
  283. ids = flat.filter((val, i) => modelNames[i] === modelName);
  284. }
  285. if (!available[modelName] || currentOptions.perDocumentLimit != null || get(currentOptions, 'options.perDocumentLimit') != null) {
  286. currentOptions = {
  287. model: Model
  288. };
  289. if (isVirtual && get(virtual, 'options.options')) {
  290. currentOptions.options = utils.clone(virtual.options.options);
  291. } else if (schemaOptions != null) {
  292. currentOptions.options = Object.assign({}, schemaOptions);
  293. }
  294. utils.merge(currentOptions, options);
  295. // Used internally for checking what model was used to populate this
  296. // path.
  297. options[populateModelSymbol] = Model;
  298. available[modelName] = {
  299. model: Model,
  300. options: currentOptions,
  301. match: hasMatchFunction ? [match] : match,
  302. docs: [doc],
  303. ids: [ids],
  304. allIds: [ret],
  305. localField: new Set([localField]),
  306. foreignField: new Set([foreignField]),
  307. justOne: justOne,
  308. isVirtual: isVirtual,
  309. virtual: virtual,
  310. count: count,
  311. [populateModelSymbol]: Model
  312. };
  313. map.push(available[modelName]);
  314. } else {
  315. available[modelName].localField.add(localField);
  316. available[modelName].foreignField.add(foreignField);
  317. available[modelName].docs.push(doc);
  318. available[modelName].ids.push(ids);
  319. available[modelName].allIds.push(ret);
  320. if (hasMatchFunction) {
  321. available[modelName].match.push(match);
  322. }
  323. }
  324. }
  325. }
  326. return map;
  327. function _getModelNames(doc, schema) {
  328. let modelNames;
  329. let discriminatorKey;
  330. let isRefPath = false;
  331. let justOne = null;
  332. if (schema && schema.caster) {
  333. schema = schema.caster;
  334. }
  335. if (schema && schema.$isSchemaMap) {
  336. schema = schema.$__schemaType;
  337. }
  338. if (!schema && model.discriminators) {
  339. discriminatorKey = model.schema.discriminatorMapping.key;
  340. }
  341. refPath = schema && schema.options && schema.options.refPath;
  342. const normalizedRefPath = normalizeRefPath(refPath, doc, options.path);
  343. if (modelNameFromQuery) {
  344. modelNames = [modelNameFromQuery]; // query options
  345. } else if (normalizedRefPath) {
  346. if (options._queryProjection != null && isPathExcluded(options._queryProjection, normalizedRefPath)) {
  347. throw new MongooseError('refPath `' + normalizedRefPath +
  348. '` must not be excluded in projection, got ' +
  349. util.inspect(options._queryProjection));
  350. }
  351. if (modelSchema.virtuals.hasOwnProperty(normalizedRefPath) && doc.$__ == null) {
  352. modelNames = [modelSchema.virtuals[normalizedRefPath].applyGetters(void 0, doc)];
  353. } else {
  354. modelNames = utils.getValue(normalizedRefPath, doc);
  355. }
  356. if (Array.isArray(modelNames)) {
  357. modelNames = utils.array.flatten(modelNames);
  358. }
  359. isRefPath = true;
  360. } else {
  361. let modelForCurrentDoc = model;
  362. let schemaForCurrentDoc;
  363. let discriminatorValue;
  364. if (!schema && discriminatorKey && (discriminatorValue = utils.getValue(discriminatorKey, doc))) {
  365. // `modelNameForFind` is the discriminator value, so we might need
  366. // find the discriminated model name
  367. const discriminatorModel = getDiscriminatorByValue(model.discriminators, discriminatorValue) || model;
  368. if (discriminatorModel != null) {
  369. modelForCurrentDoc = discriminatorModel;
  370. } else {
  371. try {
  372. modelForCurrentDoc = model.db.model(discriminatorValue);
  373. } catch (error) {
  374. return error;
  375. }
  376. }
  377. schemaForCurrentDoc = modelForCurrentDoc.schema._getSchema(options.path);
  378. if (schemaForCurrentDoc && schemaForCurrentDoc.caster) {
  379. schemaForCurrentDoc = schemaForCurrentDoc.caster;
  380. }
  381. } else {
  382. schemaForCurrentDoc = schema;
  383. }
  384. const _virtualRes = getVirtual(modelForCurrentDoc.schema, options.path);
  385. const virtual = _virtualRes == null ? null : _virtualRes.virtual;
  386. if (schemaForCurrentDoc != null) {
  387. justOne = !schemaForCurrentDoc.$isMongooseArray && !schemaForCurrentDoc._arrayPath;
  388. }
  389. let ref;
  390. let refPath;
  391. if ((ref = get(schemaForCurrentDoc, 'options.ref')) != null) {
  392. ref = handleRefFunction(ref, doc);
  393. modelNames = [ref];
  394. } else if ((ref = get(virtual, 'options.ref')) != null) {
  395. ref = handleRefFunction(ref, doc);
  396. // When referencing nested arrays, the ref should be an Array
  397. // of modelNames.
  398. if (Array.isArray(ref)) {
  399. modelNames = ref;
  400. } else {
  401. modelNames = [ref];
  402. }
  403. isVirtual = true;
  404. } else if ((refPath = get(schemaForCurrentDoc, 'options.refPath')) != null) {
  405. isRefPath = true;
  406. refPath = normalizeRefPath(refPath, doc, options.path);
  407. modelNames = utils.getValue(refPath, doc);
  408. if (Array.isArray(modelNames)) {
  409. modelNames = utils.array.flatten(modelNames);
  410. }
  411. } else {
  412. // We may have a discriminator, in which case we don't want to
  413. // populate using the base model by default
  414. modelNames = discriminatorKey ? null : [model.modelName];
  415. }
  416. }
  417. if (!modelNames) {
  418. return { modelNames: modelNames, isRefPath: isRefPath, refPath: normalizedRefPath, justOne: justOne };
  419. }
  420. if (!Array.isArray(modelNames)) {
  421. modelNames = [modelNames];
  422. }
  423. return { modelNames: modelNames, isRefPath: isRefPath, refPath: normalizedRefPath, justOne: justOne };
  424. }
  425. };
  426. /*!
  427. * ignore
  428. */
  429. function handleRefFunction(ref, doc) {
  430. if (typeof ref === 'function' && !ref[modelSymbol]) {
  431. return ref.call(doc, doc);
  432. }
  433. return ref;
  434. }
  435. /*!
  436. * Retrieve the _id of `val` if a Document or Array of Documents.
  437. *
  438. * @param {Array|Document|Any} val
  439. * @return {Array|Document|Any}
  440. */
  441. function convertTo_id(val, schema) {
  442. if (val != null && val.$__ != null) {
  443. return val._id;
  444. }
  445. if (val != null && val._id != null && (schema == null || !schema.$isSchemaMap)) {
  446. return val._id;
  447. }
  448. if (Array.isArray(val)) {
  449. for (let i = 0; i < val.length; ++i) {
  450. if (val[i] != null && val[i].$__ != null) {
  451. val[i] = val[i]._id;
  452. }
  453. }
  454. if (val.isMongooseArray && val.$schema()) {
  455. return val.$schema()._castForPopulate(val, val.$parent());
  456. }
  457. return [].concat(val);
  458. }
  459. // `populate('map')` may be an object if populating on a doc that hasn't
  460. // been hydrated yet
  461. if (val != null &&
  462. val.constructor.name === 'Object' &&
  463. // The intent here is we should only flatten the object if we expect
  464. // to get a Map in the end. Avoid doing this for mixed types.
  465. (schema == null || schema[schemaMixedSymbol] == null)) {
  466. const ret = [];
  467. for (const key of Object.keys(val)) {
  468. ret.push(val[key]);
  469. }
  470. return ret;
  471. }
  472. // If doc has already been hydrated, e.g. `doc.populate('map').execPopulate()`
  473. // then `val` will already be a map
  474. if (val instanceof Map) {
  475. return Array.from(val.values());
  476. }
  477. return val;
  478. }