queryhelpers.js 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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, options) {
  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.discriminators, 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. if (typeof options === 'undefined') {
  93. options = {};
  94. options.defaults = true;
  95. }
  96. return new model(undefined, fields, {
  97. skipId: true,
  98. isNew: false,
  99. willInit: true,
  100. defaults: options.defaults
  101. });
  102. };
  103. /*!
  104. * ignore
  105. */
  106. exports.applyPaths = function applyPaths(fields, schema) {
  107. // determine if query is selecting or excluding fields
  108. let exclude;
  109. let keys;
  110. let keyIndex;
  111. if (fields) {
  112. keys = Object.keys(fields);
  113. keyIndex = keys.length;
  114. while (keyIndex--) {
  115. if (keys[keyIndex][0] === '+') {
  116. continue;
  117. }
  118. const field = fields[keys[keyIndex]];
  119. // Skip `$meta` and `$slice`
  120. if (!isDefiningProjection(field)) {
  121. continue;
  122. }
  123. exclude = !field;
  124. break;
  125. }
  126. }
  127. // if selecting, apply default schematype select:true fields
  128. // if excluding, apply schematype select:false fields
  129. const selected = [];
  130. const excluded = [];
  131. const stack = [];
  132. analyzeSchema(schema);
  133. switch (exclude) {
  134. case true:
  135. for (const fieldName of excluded) {
  136. fields[fieldName] = 0;
  137. }
  138. break;
  139. case false:
  140. if (schema &&
  141. schema.paths['_id'] &&
  142. schema.paths['_id'].options &&
  143. schema.paths['_id'].options.select === false) {
  144. fields._id = 0;
  145. }
  146. for (const fieldName of selected) {
  147. fields[fieldName] = fields[fieldName] || 1;
  148. }
  149. break;
  150. case undefined:
  151. if (fields == null) {
  152. break;
  153. }
  154. // Any leftover plus paths must in the schema, so delete them (gh-7017)
  155. for (const key of Object.keys(fields || {})) {
  156. if (key.startsWith('+')) {
  157. delete fields[key];
  158. }
  159. }
  160. // user didn't specify fields, implies returning all fields.
  161. // only need to apply excluded fields and delete any plus paths
  162. for (const fieldName of excluded) {
  163. fields[fieldName] = 0;
  164. }
  165. break;
  166. }
  167. function analyzeSchema(schema, prefix) {
  168. prefix || (prefix = '');
  169. // avoid recursion
  170. if (stack.indexOf(schema) !== -1) {
  171. return [];
  172. }
  173. stack.push(schema);
  174. const addedPaths = [];
  175. schema.eachPath(function(path, type) {
  176. if (prefix) path = prefix + '.' + path;
  177. let addedPath = analyzePath(path, type);
  178. // arrays
  179. if (addedPath == null && type.$isMongooseArray && !type.$isMongooseDocumentArray) {
  180. addedPath = analyzePath(path, type.caster);
  181. }
  182. if (addedPath != null) {
  183. addedPaths.push(addedPath);
  184. }
  185. // nested schemas
  186. if (type.schema) {
  187. const _addedPaths = analyzeSchema(type.schema, path);
  188. // Special case: if discriminator key is the only field that would
  189. // be projected in, remove it.
  190. if (exclude === false) {
  191. checkEmbeddedDiscriminatorKeyProjection(fields, path, type.schema,
  192. selected, _addedPaths);
  193. }
  194. }
  195. });
  196. stack.pop();
  197. return addedPaths;
  198. }
  199. function analyzePath(path, type) {
  200. const plusPath = '+' + path;
  201. const hasPlusPath = fields && plusPath in fields;
  202. if (hasPlusPath) {
  203. // forced inclusion
  204. delete fields[plusPath];
  205. }
  206. if (typeof type.selected !== 'boolean') return;
  207. if (hasPlusPath) {
  208. // forced inclusion
  209. delete fields[plusPath];
  210. // if there are other fields being included, add this one
  211. // if no other included fields, leave this out (implied inclusion)
  212. if (exclude === false && keys.length > 1 && !~keys.indexOf(path)) {
  213. fields[path] = 1;
  214. }
  215. return;
  216. }
  217. // check for parent exclusions
  218. const pieces = path.split('.');
  219. let cur = '';
  220. for (let i = 0; i < pieces.length; ++i) {
  221. cur += cur.length ? '.' + pieces[i] : pieces[i];
  222. if (excluded.indexOf(cur) !== -1) {
  223. return;
  224. }
  225. }
  226. // Special case: if user has included a parent path of a discriminator key,
  227. // don't explicitly project in the discriminator key because that will
  228. // project out everything else under the parent path
  229. if (!exclude && get(type, 'options.$skipDiscriminatorCheck', false)) {
  230. let cur = '';
  231. for (let i = 0; i < pieces.length; ++i) {
  232. cur += (cur.length === 0 ? '' : '.') + pieces[i];
  233. const projection = get(fields, cur, false) || get(fields, cur + '.$', false);
  234. if (projection && typeof projection !== 'object') {
  235. return;
  236. }
  237. }
  238. }
  239. (type.selected ? selected : excluded).push(path);
  240. return path;
  241. }
  242. };
  243. /*!
  244. * Set each path query option to lean
  245. *
  246. * @param {Object} option
  247. */
  248. function makeLean(val) {
  249. return function(option) {
  250. option.options || (option.options = {});
  251. if (val != null && Array.isArray(val.virtuals)) {
  252. val = Object.assign({}, val);
  253. val.virtuals = val.virtuals.
  254. filter(path => typeof path === 'string' && path.startsWith(option.path + '.')).
  255. map(path => path.slice(option.path.length + 1));
  256. }
  257. option.options.lean = val;
  258. };
  259. }
  260. /*!
  261. * Handle the `WriteOpResult` from the server
  262. */
  263. exports.handleDeleteWriteOpResult = function handleDeleteWriteOpResult(callback) {
  264. return function _handleDeleteWriteOpResult(error, res) {
  265. if (error) {
  266. return callback(error);
  267. }
  268. const mongooseResult = Object.assign({}, res.result);
  269. if (get(res, 'result.n', null) != null) {
  270. mongooseResult.deletedCount = res.result.n;
  271. }
  272. if (res.deletedCount != null) {
  273. mongooseResult.deletedCount = res.deletedCount;
  274. }
  275. return callback(null, mongooseResult);
  276. };
  277. };