updateValidators.js 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. 'use strict';
  2. /*!
  3. * Module dependencies.
  4. */
  5. const ValidationError = require('../error/validation');
  6. const cleanPositionalOperators = require('./schema/cleanPositionalOperators');
  7. const flatten = require('./common').flatten;
  8. const modifiedPaths = require('./common').modifiedPaths;
  9. /**
  10. * Applies validators and defaults to update and findOneAndUpdate operations,
  11. * specifically passing a null doc as `this` to validators and defaults
  12. *
  13. * @param {Query} query
  14. * @param {Schema} schema
  15. * @param {Object} castedDoc
  16. * @param {Object} options
  17. * @method runValidatorsOnUpdate
  18. * @api private
  19. */
  20. module.exports = function(query, schema, castedDoc, options, callback) {
  21. const keys = Object.keys(castedDoc || {});
  22. let updatedKeys = {};
  23. let updatedValues = {};
  24. const isPull = {};
  25. const arrayAtomicUpdates = {};
  26. const numKeys = keys.length;
  27. let hasDollarUpdate = false;
  28. const modified = {};
  29. let currentUpdate;
  30. let key;
  31. let i;
  32. for (i = 0; i < numKeys; ++i) {
  33. if (keys[i].startsWith('$')) {
  34. hasDollarUpdate = true;
  35. if (keys[i] === '$push' || keys[i] === '$addToSet') {
  36. const _keys = Object.keys(castedDoc[keys[i]]);
  37. for (let ii = 0; ii < _keys.length; ++ii) {
  38. currentUpdate = castedDoc[keys[i]][_keys[ii]];
  39. if (currentUpdate && currentUpdate.$each) {
  40. arrayAtomicUpdates[_keys[ii]] = (arrayAtomicUpdates[_keys[ii]] || []).
  41. concat(currentUpdate.$each);
  42. } else {
  43. arrayAtomicUpdates[_keys[ii]] = (arrayAtomicUpdates[_keys[ii]] || []).
  44. concat([currentUpdate]);
  45. }
  46. }
  47. continue;
  48. }
  49. modifiedPaths(castedDoc[keys[i]], '', modified);
  50. const flat = flatten(castedDoc[keys[i]], null, null, schema);
  51. const paths = Object.keys(flat);
  52. const numPaths = paths.length;
  53. for (let j = 0; j < numPaths; ++j) {
  54. const updatedPath = cleanPositionalOperators(paths[j]);
  55. key = keys[i];
  56. // With `$pull` we might flatten `$in`. Skip stuff nested under `$in`
  57. // for the rest of the logic, it will get handled later.
  58. if (updatedPath.includes('$')) {
  59. continue;
  60. }
  61. if (key === '$set' || key === '$setOnInsert' ||
  62. key === '$pull' || key === '$pullAll') {
  63. updatedValues[updatedPath] = flat[paths[j]];
  64. isPull[updatedPath] = key === '$pull' || key === '$pullAll';
  65. } else if (key === '$unset') {
  66. updatedValues[updatedPath] = undefined;
  67. }
  68. updatedKeys[updatedPath] = true;
  69. }
  70. }
  71. }
  72. if (!hasDollarUpdate) {
  73. modifiedPaths(castedDoc, '', modified);
  74. updatedValues = flatten(castedDoc, null, null, schema);
  75. updatedKeys = Object.keys(updatedValues);
  76. }
  77. const updates = Object.keys(updatedValues);
  78. const numUpdates = updates.length;
  79. const validatorsToExecute = [];
  80. const validationErrors = [];
  81. const alreadyValidated = [];
  82. const context = query;
  83. function iter(i, v) {
  84. const schemaPath = schema._getSchema(updates[i]);
  85. if (schemaPath == null) {
  86. return;
  87. }
  88. if (schemaPath.instance === 'Mixed' && schemaPath.path !== updates[i]) {
  89. return;
  90. }
  91. if (v && Array.isArray(v.$in)) {
  92. v.$in.forEach((v, i) => {
  93. validatorsToExecute.push(function(callback) {
  94. schemaPath.doValidate(
  95. v,
  96. function(err) {
  97. if (err) {
  98. err.path = updates[i] + '.$in.' + i;
  99. validationErrors.push(err);
  100. }
  101. callback(null);
  102. },
  103. context,
  104. { updateValidator: true });
  105. });
  106. });
  107. } else {
  108. if (isPull[updates[i]] &&
  109. schemaPath.$isMongooseArray) {
  110. return;
  111. }
  112. if (schemaPath.$isMongooseDocumentArrayElement && v != null && v.$__ != null) {
  113. alreadyValidated.push(updates[i]);
  114. validatorsToExecute.push(function(callback) {
  115. schemaPath.doValidate(v, function(err) {
  116. if (err) {
  117. if (err.errors) {
  118. for (const key of Object.keys(err.errors)) {
  119. const _err = err.errors[key];
  120. _err.path = updates[i] + '.' + key;
  121. validationErrors.push(_err);
  122. }
  123. } else {
  124. err.path = updates[i];
  125. validationErrors.push(err);
  126. }
  127. }
  128. return callback(null);
  129. }, context, { updateValidator: true });
  130. });
  131. } else {
  132. validatorsToExecute.push(function(callback) {
  133. for (const path of alreadyValidated) {
  134. if (updates[i].startsWith(path + '.')) {
  135. return callback(null);
  136. }
  137. }
  138. schemaPath.doValidate(v, function(err) {
  139. if (schemaPath.schema != null &&
  140. schemaPath.schema.options.storeSubdocValidationError === false &&
  141. err instanceof ValidationError) {
  142. return callback(null);
  143. }
  144. if (err) {
  145. err.path = updates[i];
  146. validationErrors.push(err);
  147. }
  148. callback(null);
  149. }, context, { updateValidator: true });
  150. });
  151. }
  152. }
  153. }
  154. for (i = 0; i < numUpdates; ++i) {
  155. iter(i, updatedValues[updates[i]]);
  156. }
  157. const arrayUpdates = Object.keys(arrayAtomicUpdates);
  158. for (const arrayUpdate of arrayUpdates) {
  159. let schemaPath = schema._getSchema(arrayUpdate);
  160. if (schemaPath && schemaPath.$isMongooseDocumentArray) {
  161. validatorsToExecute.push(function(callback) {
  162. schemaPath.doValidate(
  163. arrayAtomicUpdates[arrayUpdate],
  164. getValidationCallback(arrayUpdate, validationErrors, callback),
  165. options && options.context === 'query' ? query : null);
  166. });
  167. } else {
  168. schemaPath = schema._getSchema(arrayUpdate + '.0');
  169. for (const atomicUpdate of arrayAtomicUpdates[arrayUpdate]) {
  170. validatorsToExecute.push(function(callback) {
  171. schemaPath.doValidate(
  172. atomicUpdate,
  173. getValidationCallback(arrayUpdate, validationErrors, callback),
  174. options && options.context === 'query' ? query : null,
  175. { updateValidator: true });
  176. });
  177. }
  178. }
  179. }
  180. if (callback != null) {
  181. let numValidators = validatorsToExecute.length;
  182. if (numValidators === 0) {
  183. return _done(callback);
  184. }
  185. for (const validator of validatorsToExecute) {
  186. validator(function() {
  187. if (--numValidators <= 0) {
  188. _done(callback);
  189. }
  190. });
  191. }
  192. return;
  193. }
  194. return function(callback) {
  195. let numValidators = validatorsToExecute.length;
  196. if (numValidators === 0) {
  197. return _done(callback);
  198. }
  199. for (const validator of validatorsToExecute) {
  200. validator(function() {
  201. if (--numValidators <= 0) {
  202. _done(callback);
  203. }
  204. });
  205. }
  206. };
  207. function _done(callback) {
  208. if (validationErrors.length) {
  209. const err = new ValidationError(null);
  210. for (const validationError of validationErrors) {
  211. err.addError(validationError.path, validationError);
  212. }
  213. return callback(err);
  214. }
  215. callback(null);
  216. }
  217. function getValidationCallback(arrayUpdate, validationErrors, callback) {
  218. return function(err) {
  219. if (err) {
  220. err.path = arrayUpdate;
  221. validationErrors.push(err);
  222. }
  223. callback(null);
  224. };
  225. }
  226. };