queryhelpers.js 8.0 KB

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