queryhelpers.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. 'use strict';
  2. /*!
  3. * Module dependencies
  4. */
  5. const checkEmbeddedDiscriminatorKeyProjection =
  6. require('./helpers/discriminator/checkEmbeddedDiscriminatorKeyProjection');
  7. const get = require('./helpers/get');
  8. const getDiscriminatorByValue =
  9. require('./helpers/discriminator/getDiscriminatorByValue');
  10. const isDefiningProjection = require('./helpers/projection/isDefiningProjection');
  11. const clone = require('./helpers/clone');
  12. /*!
  13. * Prepare a set of path options for query population.
  14. *
  15. * @param {Query} query
  16. * @param {Object} options
  17. * @return {Array}
  18. */
  19. exports.preparePopulationOptions = function preparePopulationOptions(query, options) {
  20. const _populate = query.options.populate;
  21. const pop = Object.keys(_populate).reduce((vals, key) => vals.concat([_populate[key]]), []);
  22. // lean options should trickle through all queries
  23. if (options.lean != null) {
  24. pop
  25. .filter(p => (p && p.options && p.options.lean) == null)
  26. .forEach(makeLean(options.lean));
  27. }
  28. pop.forEach(opts => {
  29. opts._localModel = query.model;
  30. });
  31. return pop;
  32. };
  33. /*!
  34. * Prepare a set of path options for query population. This is the MongooseQuery
  35. * version
  36. *
  37. * @param {Query} query
  38. * @param {Object} options
  39. * @return {Array}
  40. */
  41. exports.preparePopulationOptionsMQ = function preparePopulationOptionsMQ(query, options) {
  42. const _populate = query._mongooseOptions.populate;
  43. const pop = Object.keys(_populate).reduce((vals, key) => vals.concat([_populate[key]]), []);
  44. // lean options should trickle through all queries
  45. if (options.lean != null) {
  46. pop
  47. .filter(p => (p && p.options && p.options.lean) == null)
  48. .forEach(makeLean(options.lean));
  49. }
  50. const session = query && query.options && query.options.session || null;
  51. if (session != null) {
  52. pop.forEach(path => {
  53. if (path.options == null) {
  54. path.options = { session: session };
  55. return;
  56. }
  57. if (!('session' in path.options)) {
  58. path.options.session = session;
  59. }
  60. });
  61. }
  62. const projection = query._fieldsForExec();
  63. pop.forEach(p => {
  64. p._queryProjection = projection;
  65. });
  66. pop.forEach(opts => {
  67. opts._localModel = query.model;
  68. });
  69. return pop;
  70. };
  71. /*!
  72. * If the document is a mapped discriminator type, it returns a model instance for that type, otherwise,
  73. * it returns an instance of the given model.
  74. *
  75. * @param {Model} model
  76. * @param {Object} doc
  77. * @param {Object} fields
  78. *
  79. * @return {Document}
  80. */
  81. exports.createModel = function createModel(model, doc, fields, userProvidedFields, options) {
  82. model.hooks.execPreSync('createModel', doc);
  83. const discriminatorMapping = model.schema ?
  84. model.schema.discriminatorMapping :
  85. null;
  86. const key = discriminatorMapping && discriminatorMapping.isRoot ?
  87. discriminatorMapping.key :
  88. null;
  89. const value = doc[key];
  90. if (key && value && model.discriminators) {
  91. const discriminator = model.discriminators[value] || getDiscriminatorByValue(model.discriminators, value);
  92. if (discriminator) {
  93. const _fields = clone(userProvidedFields);
  94. exports.applyPaths(_fields, discriminator.schema);
  95. return new discriminator(undefined, _fields, true);
  96. }
  97. }
  98. const _opts = {
  99. skipId: true,
  100. isNew: false,
  101. willInit: true
  102. };
  103. if (options != null && 'defaults' in options) {
  104. _opts.defaults = options.defaults;
  105. }
  106. return new model(undefined, fields, _opts);
  107. };
  108. /*!
  109. * ignore
  110. */
  111. exports.createModelAndInit = function createModelAndInit(model, doc, fields, userProvidedFields, options, populatedIds, callback) {
  112. const initOpts = populatedIds ?
  113. { populated: populatedIds } :
  114. undefined;
  115. const casted = exports.createModel(model, doc, fields, userProvidedFields, options);
  116. try {
  117. casted.$init(doc, initOpts, callback);
  118. } catch (error) {
  119. callback(error, casted);
  120. }
  121. };
  122. /*!
  123. * ignore
  124. */
  125. exports.applyPaths = function applyPaths(fields, schema) {
  126. // determine if query is selecting or excluding fields
  127. let exclude;
  128. let keys;
  129. let keyIndex;
  130. if (fields) {
  131. keys = Object.keys(fields);
  132. keyIndex = keys.length;
  133. while (keyIndex--) {
  134. if (keys[keyIndex][0] === '+') {
  135. continue;
  136. }
  137. const field = fields[keys[keyIndex]];
  138. // Skip `$meta` and `$slice`
  139. if (!isDefiningProjection(field)) {
  140. continue;
  141. }
  142. exclude = !field;
  143. break;
  144. }
  145. }
  146. // if selecting, apply default schematype select:true fields
  147. // if excluding, apply schematype select:false fields
  148. const selected = [];
  149. const excluded = [];
  150. const stack = [];
  151. analyzeSchema(schema);
  152. switch (exclude) {
  153. case true:
  154. for (const fieldName of excluded) {
  155. fields[fieldName] = 0;
  156. }
  157. break;
  158. case false:
  159. if (schema &&
  160. schema.paths['_id'] &&
  161. schema.paths['_id'].options &&
  162. schema.paths['_id'].options.select === false) {
  163. fields._id = 0;
  164. }
  165. for (const fieldName of selected) {
  166. fields[fieldName] = fields[fieldName] || 1;
  167. }
  168. break;
  169. case undefined:
  170. if (fields == null) {
  171. break;
  172. }
  173. // Any leftover plus paths must in the schema, so delete them (gh-7017)
  174. for (const key of Object.keys(fields || {})) {
  175. if (key.startsWith('+')) {
  176. delete fields[key];
  177. }
  178. }
  179. // user didn't specify fields, implies returning all fields.
  180. // only need to apply excluded fields and delete any plus paths
  181. for (const fieldName of excluded) {
  182. if (fields[fieldName] != null) {
  183. // Skip applying default projections to fields with non-defining
  184. // projections, like `$slice`
  185. continue;
  186. }
  187. fields[fieldName] = 0;
  188. }
  189. break;
  190. }
  191. function analyzeSchema(schema, prefix) {
  192. prefix || (prefix = '');
  193. // avoid recursion
  194. if (stack.indexOf(schema) !== -1) {
  195. return [];
  196. }
  197. stack.push(schema);
  198. const addedPaths = [];
  199. schema.eachPath(function(path, type) {
  200. if (prefix) path = prefix + '.' + path;
  201. if (type.$isSchemaMap || path.endsWith('.$*')) {
  202. return;
  203. }
  204. let addedPath = analyzePath(path, type);
  205. // arrays
  206. if (addedPath == null && !Array.isArray(type) && type.$isMongooseArray && !type.$isMongooseDocumentArray) {
  207. addedPath = analyzePath(path, type.caster);
  208. }
  209. if (addedPath != null) {
  210. addedPaths.push(addedPath);
  211. }
  212. // nested schemas
  213. if (type.schema) {
  214. const _addedPaths = analyzeSchema(type.schema, path);
  215. // Special case: if discriminator key is the only field that would
  216. // be projected in, remove it.
  217. if (exclude === false) {
  218. checkEmbeddedDiscriminatorKeyProjection(fields, path, type.schema,
  219. selected, _addedPaths);
  220. }
  221. }
  222. });
  223. stack.pop();
  224. return addedPaths;
  225. }
  226. function analyzePath(path, type) {
  227. const plusPath = '+' + path;
  228. const hasPlusPath = fields && plusPath in fields;
  229. if (hasPlusPath) {
  230. // forced inclusion
  231. delete fields[plusPath];
  232. }
  233. if (typeof type.selected !== 'boolean') {
  234. return;
  235. }
  236. // If set to 0, we're explicitly excluding the discriminator key. Can't do this for all fields,
  237. // because we have tests that assert that using `-path` to exclude schema-level `select: true`
  238. // fields counts as an exclusive projection. See gh-11546
  239. if (exclude && type.selected && path === schema.options.discriminatorKey && fields[path] != null && !fields[path]) {
  240. delete fields[path];
  241. return;
  242. }
  243. if (hasPlusPath) {
  244. // forced inclusion
  245. delete fields[plusPath];
  246. // if there are other fields being included, add this one
  247. // if no other included fields, leave this out (implied inclusion)
  248. if (exclude === false && keys.length > 1 && !~keys.indexOf(path)) {
  249. fields[path] = 1;
  250. }
  251. return;
  252. }
  253. // check for parent exclusions
  254. const pieces = path.split('.');
  255. let cur = '';
  256. for (let i = 0; i < pieces.length; ++i) {
  257. cur += cur.length ? '.' + pieces[i] : pieces[i];
  258. if (excluded.indexOf(cur) !== -1) {
  259. return;
  260. }
  261. }
  262. // Special case: if user has included a parent path of a discriminator key,
  263. // don't explicitly project in the discriminator key because that will
  264. // project out everything else under the parent path
  265. if (!exclude && (type && type.options && type.options.$skipDiscriminatorCheck || false)) {
  266. let cur = '';
  267. for (let i = 0; i < pieces.length; ++i) {
  268. cur += (cur.length === 0 ? '' : '.') + pieces[i];
  269. const projection = get(fields, cur, false) || get(fields, cur + '.$', false);
  270. if (projection && typeof projection !== 'object') {
  271. return;
  272. }
  273. }
  274. }
  275. (type.selected ? selected : excluded).push(path);
  276. return path;
  277. }
  278. };
  279. /*!
  280. * Set each path query option to lean
  281. *
  282. * @param {Object} option
  283. */
  284. function makeLean(val) {
  285. return function(option) {
  286. option.options || (option.options = {});
  287. if (val != null && Array.isArray(val.virtuals)) {
  288. val = Object.assign({}, val);
  289. val.virtuals = val.virtuals.
  290. filter(path => typeof path === 'string' && path.startsWith(option.path + '.')).
  291. map(path => path.slice(option.path.length + 1));
  292. }
  293. option.options.lean = val;
  294. };
  295. }