assignVals.js 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. 'use strict';
  2. const MongooseMap = require('../../types/map');
  3. const SkipPopulateValue = require('./SkipPopulateValue');
  4. const assignRawDocsToIdStructure = require('./assignRawDocsToIdStructure');
  5. const get = require('../get');
  6. const getVirtual = require('./getVirtual');
  7. const leanPopulateMap = require('./leanPopulateMap');
  8. const lookupLocalFields = require('./lookupLocalFields');
  9. const markArraySubdocsPopulated = require('./markArraySubdocsPopulated');
  10. const mpath = require('mpath');
  11. const sift = require('sift').default;
  12. const utils = require('../../utils');
  13. const { populateModelSymbol } = require('../symbols');
  14. module.exports = function assignVals(o) {
  15. // Options that aren't explicitly listed in `populateOptions`
  16. const userOptions = Object.assign({}, get(o, 'allOptions.options.options'), get(o, 'allOptions.options'));
  17. // `o.options` contains options explicitly listed in `populateOptions`, like
  18. // `match` and `limit`.
  19. const populateOptions = Object.assign({}, o.options, userOptions, {
  20. justOne: o.justOne
  21. });
  22. populateOptions.$nullIfNotFound = o.isVirtual;
  23. const populatedModel = o.populatedModel;
  24. const originalIds = [].concat(o.rawIds);
  25. // replace the original ids in our intermediate _ids structure
  26. // with the documents found by query
  27. o.allIds = [].concat(o.allIds);
  28. assignRawDocsToIdStructure(o.rawIds, o.rawDocs, o.rawOrder, populateOptions);
  29. // now update the original documents being populated using the
  30. // result structure that contains real documents.
  31. const docs = o.docs;
  32. const rawIds = o.rawIds;
  33. const options = o.options;
  34. const count = o.count && o.isVirtual;
  35. let i;
  36. function setValue(val) {
  37. if (count) {
  38. return val;
  39. }
  40. if (val instanceof SkipPopulateValue) {
  41. return val.val;
  42. }
  43. if (val === void 0) {
  44. return val;
  45. }
  46. const _allIds = o.allIds[i];
  47. if (o.justOne === true && Array.isArray(val)) {
  48. // Might be an embedded discriminator (re: gh-9244) with multiple models, so make sure to pick the right
  49. // model before assigning.
  50. const ret = [];
  51. for (const doc of val) {
  52. const _docPopulatedModel = leanPopulateMap.get(doc);
  53. if (_docPopulatedModel == null || _docPopulatedModel === populatedModel) {
  54. ret.push(doc);
  55. }
  56. }
  57. // Since we don't want to have to create a new mongoosearray, make sure to
  58. // modify the array in place
  59. while (val.length > ret.length) {
  60. Array.prototype.pop.apply(val, []);
  61. }
  62. for (let i = 0; i < ret.length; ++i) {
  63. val[i] = ret[i];
  64. }
  65. return valueFilter(val[0], options, populateOptions, _allIds);
  66. } else if (o.justOne === false && !Array.isArray(val)) {
  67. return valueFilter([val], options, populateOptions, _allIds);
  68. }
  69. return valueFilter(val, options, populateOptions, _allIds);
  70. }
  71. for (i = 0; i < docs.length; ++i) {
  72. const _path = o.path.endsWith('.$*') ? o.path.slice(0, -3) : o.path;
  73. const existingVal = mpath.get(_path, docs[i], lookupLocalFields);
  74. if (existingVal == null && !getVirtual(o.originalModel.schema, _path)) {
  75. continue;
  76. }
  77. let valueToSet;
  78. if (count) {
  79. valueToSet = numDocs(rawIds[i]);
  80. } else if (Array.isArray(o.match)) {
  81. valueToSet = Array.isArray(rawIds[i]) ?
  82. rawIds[i].filter(sift(o.match[i])) :
  83. [rawIds[i]].filter(sift(o.match[i]))[0];
  84. } else {
  85. valueToSet = rawIds[i];
  86. }
  87. // If we're populating a map, the existing value will be an object, so
  88. // we need to transform again
  89. const originalSchema = o.originalModel.schema;
  90. const isDoc = get(docs[i], '$__', null) != null;
  91. let isMap = isDoc ?
  92. existingVal instanceof Map :
  93. utils.isPOJO(existingVal);
  94. // If we pass the first check, also make sure the local field's schematype
  95. // is map (re: gh-6460)
  96. isMap = isMap && get(originalSchema._getSchema(_path), '$isSchemaMap');
  97. if (!o.isVirtual && isMap) {
  98. const _keys = existingVal instanceof Map ?
  99. Array.from(existingVal.keys()) :
  100. Object.keys(existingVal);
  101. valueToSet = valueToSet.reduce((cur, v, i) => {
  102. cur.set(_keys[i], v);
  103. return cur;
  104. }, new Map());
  105. }
  106. if (isDoc && Array.isArray(valueToSet)) {
  107. for (const val of valueToSet) {
  108. if (val != null && val.$__ != null) {
  109. val.$__.parent = docs[i];
  110. }
  111. }
  112. } else if (isDoc && valueToSet != null && valueToSet.$__ != null) {
  113. valueToSet.$__.parent = docs[i];
  114. }
  115. if (o.isVirtual && isDoc) {
  116. docs[i].$populated(_path, o.justOne ? originalIds[0] : originalIds, o.allOptions);
  117. // If virtual populate and doc is already init-ed, need to walk through
  118. // the actual doc to set rather than setting `_doc` directly
  119. if (Array.isArray(valueToSet)) {
  120. valueToSet = valueToSet.map(v => v == null ? void 0 : v);
  121. }
  122. mpath.set(_path, valueToSet, docs[i], void 0, setValue, false);
  123. continue;
  124. }
  125. const parts = _path.split('.');
  126. let cur = docs[i];
  127. const curPath = parts[0];
  128. for (let j = 0; j < parts.length - 1; ++j) {
  129. // If we get to an array with a dotted path, like `arr.foo`, don't set
  130. // `foo` on the array.
  131. if (Array.isArray(cur) && !utils.isArrayIndex(parts[j])) {
  132. break;
  133. }
  134. if (parts[j] === '$*') {
  135. break;
  136. }
  137. if (cur[parts[j]] == null) {
  138. // If nothing to set, avoid creating an unnecessary array. Otherwise
  139. // we'll end up with a single doc in the array with only defaults.
  140. // See gh-8342, gh-8455
  141. const schematype = originalSchema._getSchema(curPath);
  142. if (valueToSet == null && schematype != null && schematype.$isMongooseArray) {
  143. break;
  144. }
  145. cur[parts[j]] = {};
  146. }
  147. cur = cur[parts[j]];
  148. // If the property in MongoDB is a primitive, we won't be able to populate
  149. // the nested path, so skip it. See gh-7545
  150. if (typeof cur !== 'object') {
  151. break;
  152. }
  153. }
  154. if (docs[i].$__) {
  155. o.allOptions.options[populateModelSymbol] = o.allOptions.model;
  156. docs[i].$populated(_path, o.unpopulatedValues[i], o.allOptions.options);
  157. if (valueToSet instanceof Map && !valueToSet.$isMongooseMap) {
  158. valueToSet = new MongooseMap(valueToSet, _path, docs[i], docs[i].schema.path(_path).$__schemaType);
  159. }
  160. }
  161. // If lean, need to check that each individual virtual respects
  162. // `justOne`, because you may have a populated virtual with `justOne`
  163. // underneath an array. See gh-6867
  164. mpath.set(_path, valueToSet, docs[i], lookupLocalFields, setValue, false);
  165. if (docs[i].$__) {
  166. markArraySubdocsPopulated(docs[i], [o.allOptions.options]);
  167. }
  168. }
  169. };
  170. function numDocs(v) {
  171. if (Array.isArray(v)) {
  172. // If setting underneath an array of populated subdocs, we may have an
  173. // array of arrays. See gh-7573
  174. if (v.some(el => Array.isArray(el))) {
  175. return v.map(el => numDocs(el));
  176. }
  177. return v.length;
  178. }
  179. return v == null ? 0 : 1;
  180. }
  181. /*!
  182. * 1) Apply backwards compatible find/findOne behavior to sub documents
  183. *
  184. * find logic:
  185. * a) filter out non-documents
  186. * b) remove _id from sub docs when user specified
  187. *
  188. * findOne
  189. * a) if no doc found, set to null
  190. * b) remove _id from sub docs when user specified
  191. *
  192. * 2) Remove _ids when specified by users query.
  193. *
  194. * background:
  195. * _ids are left in the query even when user excludes them so
  196. * that population mapping can occur.
  197. */
  198. function valueFilter(val, assignmentOpts, populateOptions, allIds) {
  199. const userSpecifiedTransform = typeof populateOptions.transform === 'function';
  200. const transform = userSpecifiedTransform ? populateOptions.transform : noop;
  201. if (Array.isArray(val)) {
  202. // find logic
  203. const ret = [];
  204. const numValues = val.length;
  205. for (let i = 0; i < numValues; ++i) {
  206. let subdoc = val[i];
  207. const _allIds = Array.isArray(allIds) ? allIds[i] : allIds;
  208. if (!isPopulatedObject(subdoc) && (!populateOptions.retainNullValues || subdoc != null) && !userSpecifiedTransform) {
  209. continue;
  210. } else if (userSpecifiedTransform) {
  211. subdoc = transform(isPopulatedObject(subdoc) ? subdoc : null, _allIds);
  212. }
  213. maybeRemoveId(subdoc, assignmentOpts);
  214. ret.push(subdoc);
  215. if (assignmentOpts.originalLimit &&
  216. ret.length >= assignmentOpts.originalLimit) {
  217. break;
  218. }
  219. }
  220. const rLen = ret.length;
  221. // Since we don't want to have to create a new mongoosearray, make sure to
  222. // modify the array in place
  223. while (val.length > rLen) {
  224. Array.prototype.pop.apply(val, []);
  225. }
  226. let i = 0;
  227. if (utils.isMongooseArray(val)) {
  228. for (i = 0; i < rLen; ++i) {
  229. val.set(i, ret[i], true);
  230. }
  231. } else {
  232. for (i = 0; i < rLen; ++i) {
  233. val[i] = ret[i];
  234. }
  235. }
  236. return val;
  237. }
  238. // findOne
  239. if (isPopulatedObject(val) || utils.isPOJO(val)) {
  240. maybeRemoveId(val, assignmentOpts);
  241. return transform(val, allIds);
  242. }
  243. if (val instanceof Map) {
  244. return val;
  245. }
  246. if (populateOptions.justOne === false) {
  247. return [];
  248. }
  249. return val == null ? transform(val, allIds) : transform(null, allIds);
  250. }
  251. /*!
  252. * Remove _id from `subdoc` if user specified "lean" query option
  253. */
  254. function maybeRemoveId(subdoc, assignmentOpts) {
  255. if (subdoc != null && assignmentOpts.excludeId) {
  256. if (typeof subdoc.$__setValue === 'function') {
  257. delete subdoc._doc._id;
  258. } else {
  259. delete subdoc._id;
  260. }
  261. }
  262. }
  263. /*!
  264. * Determine if `obj` is something we can set a populated path to. Can be a
  265. * document, a lean document, or an array/map that contains docs.
  266. */
  267. function isPopulatedObject(obj) {
  268. if (obj == null) {
  269. return false;
  270. }
  271. return Array.isArray(obj) ||
  272. obj.$isMongooseMap ||
  273. obj.$__ != null ||
  274. leanPopulateMap.has(obj);
  275. }
  276. function noop(v) {
  277. return v;
  278. }