queryhelpers.js 8.6 KB

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