queryhelpers.js 7.3 KB

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