updateValidators.js 7.1 KB

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