queryhelpers.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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 => get(p, 'options.lean') == null).
  26. forEach(makeLean(options.lean));
  27. }
  28. return pop;
  29. };
  30. /*!
  31. * Prepare a set of path options for query population. This is the MongooseQuery
  32. * version
  33. *
  34. * @param {Query} query
  35. * @param {Object} options
  36. * @return {Array}
  37. */
  38. exports.preparePopulationOptionsMQ = function preparePopulationOptionsMQ(query, options) {
  39. const _populate = query._mongooseOptions.populate;
  40. const pop = Object.keys(_populate).reduce((vals, key) => vals.concat([_populate[key]]), []);
  41. // lean options should trickle through all queries
  42. if (options.lean != null) {
  43. pop.
  44. filter(p => get(p, 'options.lean') == null).
  45. forEach(makeLean(options.lean));
  46. }
  47. const session = get(query, 'options.session', null);
  48. if (session != null) {
  49. pop.forEach(path => {
  50. if (path.options == null) {
  51. path.options = { session: session };
  52. return;
  53. }
  54. if (!('session' in path.options)) {
  55. path.options.session = session;
  56. }
  57. });
  58. }
  59. const projection = query._fieldsForExec();
  60. pop.forEach(p => {
  61. p._queryProjection = projection;
  62. });
  63. return pop;
  64. };
  65. /*!
  66. * If the document is a mapped discriminator type, it returns a model instance for that type, otherwise,
  67. * it returns an instance of the given model.
  68. *
  69. * @param {Model} model
  70. * @param {Object} doc
  71. * @param {Object} fields
  72. *
  73. * @return {Document}
  74. */
  75. exports.createModel = function createModel(model, doc, fields, userProvidedFields) {
  76. model.hooks.execPreSync('createModel', doc);
  77. const discriminatorMapping = model.schema ?
  78. model.schema.discriminatorMapping :
  79. null;
  80. const key = discriminatorMapping && discriminatorMapping.isRoot ?
  81. discriminatorMapping.key :
  82. null;
  83. const value = doc[key];
  84. if (key && value && model.discriminators) {
  85. const discriminator = model.discriminators[value] || getDiscriminatorByValue(model, value);
  86. if (discriminator) {
  87. const _fields = clone(userProvidedFields);
  88. exports.applyPaths(_fields, discriminator.schema);
  89. return new discriminator(undefined, _fields, true);
  90. }
  91. }
  92. return new model(undefined, fields, {
  93. skipId: true,
  94. isNew: false,
  95. willInit: true
  96. });
  97. };
  98. /*!
  99. * ignore
  100. */
  101. exports.applyPaths = function applyPaths(fields, schema) {
  102. // determine if query is selecting or excluding fields
  103. let exclude;
  104. let keys;
  105. let keyIndex;
  106. if (fields) {
  107. keys = Object.keys(fields);
  108. keyIndex = keys.length;
  109. while (keyIndex--) {
  110. if (keys[keyIndex][0] === '+') {
  111. continue;
  112. }
  113. const field = fields[keys[keyIndex]];
  114. // Skip `$meta` and `$slice`
  115. if (!isDefiningProjection(field)) {
  116. continue;
  117. }
  118. exclude = !field;
  119. break;
  120. }
  121. }
  122. // if selecting, apply default schematype select:true fields
  123. // if excluding, apply schematype select:false fields
  124. const selected = [];
  125. const excluded = [];
  126. const stack = [];
  127. analyzeSchema(schema);
  128. switch (exclude) {
  129. case true:
  130. for (const fieldName of excluded) {
  131. fields[fieldName] = 0;
  132. }
  133. break;
  134. case false:
  135. if (schema &&
  136. schema.paths['_id'] &&
  137. schema.paths['_id'].options &&
  138. schema.paths['_id'].options.select === false) {
  139. fields._id = 0;
  140. }
  141. for (const fieldName of selected) {
  142. fields[fieldName] = fields[fieldName] || 1;
  143. }
  144. break;
  145. case undefined:
  146. if (fields == null) {
  147. break;
  148. }
  149. // Any leftover plus paths must in the schema, so delete them (gh-7017)
  150. for (const key of Object.keys(fields || {})) {
  151. if (key.startsWith('+')) {
  152. delete fields[key];
  153. }
  154. }
  155. // user didn't specify fields, implies returning all fields.
  156. // only need to apply excluded fields and delete any plus paths
  157. for (const fieldName of excluded) {
  158. fields[fieldName] = 0;
  159. }
  160. break;
  161. }
  162. function analyzeSchema(schema, prefix) {
  163. prefix || (prefix = '');
  164. // avoid recursion
  165. if (stack.indexOf(schema) !== -1) {
  166. return [];
  167. }
  168. stack.push(schema);
  169. const addedPaths = [];
  170. schema.eachPath(function(path, type) {
  171. if (prefix) path = prefix + '.' + path;
  172. const addedPath = analyzePath(path, type);
  173. if (addedPath != null) {
  174. addedPaths.push(addedPath);
  175. }
  176. // nested schemas
  177. if (type.schema) {
  178. const _addedPaths = analyzeSchema(type.schema, path);
  179. // Special case: if discriminator key is the only field that would
  180. // be projected in, remove it.
  181. if (exclude === false) {
  182. checkEmbeddedDiscriminatorKeyProjection(fields, path, type.schema,
  183. selected, _addedPaths);
  184. }
  185. }
  186. });
  187. stack.pop();
  188. return addedPaths;
  189. }
  190. function analyzePath(path, type) {
  191. const plusPath = '+' + path;
  192. const hasPlusPath = fields && plusPath in fields;
  193. if (hasPlusPath) {
  194. // forced inclusion
  195. delete fields[plusPath];
  196. }
  197. if (typeof type.selected !== 'boolean') return;
  198. if (hasPlusPath) {
  199. // forced inclusion
  200. delete fields[plusPath];
  201. // if there are other fields being included, add this one
  202. // if no other included fields, leave this out (implied inclusion)
  203. if (exclude === false && keys.length > 1 && !~keys.indexOf(path)) {
  204. fields[path] = 1;
  205. }
  206. return;
  207. }
  208. // check for parent exclusions
  209. const pieces = path.split('.');
  210. let cur = '';
  211. for (let i = 0; i < pieces.length; ++i) {
  212. cur += cur.length ? '.' + pieces[i] : pieces[i];
  213. if (excluded.indexOf(cur) !== -1) {
  214. return;
  215. }
  216. }
  217. // Special case: if user has included a parent path of a discriminator key,
  218. // don't explicitly project in the discriminator key because that will
  219. // project out everything else under the parent path
  220. if (!exclude && get(type, 'options.$skipDiscriminatorCheck', false)) {
  221. let cur = '';
  222. for (let i = 0; i < pieces.length; ++i) {
  223. cur += (cur.length === 0 ? '' : '.') + pieces[i];
  224. const projection = get(fields, cur, false);
  225. if (projection && typeof projection !== 'object') {
  226. return;
  227. }
  228. }
  229. }
  230. (type.selected ? selected : excluded).push(path);
  231. return path;
  232. }
  233. };
  234. /*!
  235. * Set each path query option to lean
  236. *
  237. * @param {Object} option
  238. */
  239. function makeLean(val) {
  240. return function(option) {
  241. option.options || (option.options = {});
  242. option.options.lean = val;
  243. };
  244. }
  245. /*!
  246. * Handle the `WriteOpResult` from the server
  247. */
  248. exports.handleDeleteWriteOpResult = function handleDeleteWriteOpResult(callback) {
  249. return function _handleDeleteWriteOpResult(error, res) {
  250. if (error) {
  251. return callback(error);
  252. }
  253. const mongooseResult = Object.assign({}, res.result);
  254. if (get(res, 'result.n', null) != null) {
  255. mongooseResult.deletedCount = res.result.n;
  256. }
  257. if (res.deletedCount != null) {
  258. mongooseResult.deletedCount = res.deletedCount;
  259. }
  260. return callback(null, mongooseResult);
  261. };
  262. };