castUpdate.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. 'use strict';
  2. const CastError = require('../../error/cast');
  3. const StrictModeError = require('../../error/strict');
  4. const ValidationError = require('../../error/validation');
  5. const castNumber = require('../../cast/number');
  6. const getEmbeddedDiscriminatorPath = require('./getEmbeddedDiscriminatorPath');
  7. const utils = require('../../utils');
  8. /*!
  9. * Casts an update op based on the given schema
  10. *
  11. * @param {Schema} schema
  12. * @param {Object} obj
  13. * @param {Object} options
  14. * @param {Boolean} [options.overwrite] defaults to false
  15. * @param {Boolean|String} [options.strict] defaults to true
  16. * @param {Query} context passed to setters
  17. * @return {Boolean} true iff the update is non-empty
  18. */
  19. module.exports = function castUpdate(schema, obj, options, context, filter) {
  20. if (!obj) {
  21. return undefined;
  22. }
  23. const ops = Object.keys(obj);
  24. let i = ops.length;
  25. const ret = {};
  26. let hasKeys;
  27. let val;
  28. let hasDollarKey = false;
  29. const overwrite = options.overwrite;
  30. filter = filter || {};
  31. while (i--) {
  32. const op = ops[i];
  33. // if overwrite is set, don't do any of the special $set stuff
  34. if (op[0] !== '$' && !overwrite) {
  35. // fix up $set sugar
  36. if (!ret.$set) {
  37. if (obj.$set) {
  38. ret.$set = obj.$set;
  39. } else {
  40. ret.$set = {};
  41. }
  42. }
  43. ret.$set[op] = obj[op];
  44. ops.splice(i, 1);
  45. if (!~ops.indexOf('$set')) ops.push('$set');
  46. } else if (op === '$set') {
  47. if (!ret.$set) {
  48. ret[op] = obj[op];
  49. }
  50. } else {
  51. ret[op] = obj[op];
  52. }
  53. }
  54. // cast each value
  55. i = ops.length;
  56. // if we get passed {} for the update, we still need to respect that when it
  57. // is an overwrite scenario
  58. if (overwrite) {
  59. hasKeys = true;
  60. }
  61. while (i--) {
  62. const op = ops[i];
  63. val = ret[op];
  64. hasDollarKey = hasDollarKey || op.charAt(0) === '$';
  65. if (val &&
  66. typeof val === 'object' &&
  67. !Buffer.isBuffer(val) &&
  68. (!overwrite || hasDollarKey)) {
  69. hasKeys |= walkUpdatePath(schema, val, op, options, context, filter);
  70. } else if (overwrite && ret && typeof ret === 'object') {
  71. // if we are just using overwrite, cast the query and then we will
  72. // *always* return the value, even if it is an empty object. We need to
  73. // set hasKeys above because we need to account for the case where the
  74. // user passes {} and wants to clobber the whole document
  75. // Also, _walkUpdatePath expects an operation, so give it $set since that
  76. // is basically what we're doing
  77. walkUpdatePath(schema, ret, '$set', options, context, filter);
  78. } else {
  79. const msg = 'Invalid atomic update value for ' + op + '. '
  80. + 'Expected an object, received ' + typeof val;
  81. throw new Error(msg);
  82. }
  83. }
  84. return hasKeys && ret;
  85. };
  86. /*!
  87. * Walk each path of obj and cast its values
  88. * according to its schema.
  89. *
  90. * @param {Schema} schema
  91. * @param {Object} obj - part of a query
  92. * @param {String} op - the atomic operator ($pull, $set, etc)
  93. * @param {Object} options
  94. * @param {Boolean|String} [options.strict]
  95. * @param {Boolean} [options.omitUndefined]
  96. * @param {Query} context
  97. * @param {String} pref - path prefix (internal only)
  98. * @return {Bool} true if this path has keys to update
  99. * @api private
  100. */
  101. function walkUpdatePath(schema, obj, op, options, context, filter, pref) {
  102. const strict = options.strict;
  103. const prefix = pref ? pref + '.' : '';
  104. const keys = Object.keys(obj);
  105. let i = keys.length;
  106. let hasKeys = false;
  107. let schematype;
  108. let key;
  109. let val;
  110. let aggregatedError = null;
  111. let useNestedStrict;
  112. if (options.useNestedStrict === undefined) {
  113. useNestedStrict = schema.options.useNestedStrict;
  114. } else {
  115. useNestedStrict = options.useNestedStrict;
  116. }
  117. while (i--) {
  118. key = keys[i];
  119. val = obj[key];
  120. if (val && val.constructor.name === 'Object') {
  121. // watch for embedded doc schemas
  122. schematype = schema._getSchema(prefix + key);
  123. if (schematype && schematype.caster && op in castOps) {
  124. // embedded doc schema
  125. if ('$each' in val) {
  126. hasKeys = true;
  127. try {
  128. obj[key] = {
  129. $each: castUpdateVal(schematype, val.$each, op, key, context, prefix + key)
  130. };
  131. } catch (error) {
  132. aggregatedError = _handleCastError(error, context, key, aggregatedError);
  133. }
  134. if (val.$slice != null) {
  135. obj[key].$slice = val.$slice | 0;
  136. }
  137. if (val.$sort) {
  138. obj[key].$sort = val.$sort;
  139. }
  140. if (!!val.$position || val.$position === 0) {
  141. obj[key].$position = val.$position;
  142. }
  143. } else {
  144. try {
  145. obj[key] = castUpdateVal(schematype, val, op, key, context, prefix + key);
  146. } catch (error) {
  147. aggregatedError = _handleCastError(error, context, key, aggregatedError);
  148. }
  149. if (options.omitUndefined && obj[key] === void 0) {
  150. delete obj[key];
  151. continue;
  152. }
  153. hasKeys = true;
  154. }
  155. } else if ((op === '$currentDate') || (op in castOps && schematype)) {
  156. // $currentDate can take an object
  157. try {
  158. obj[key] = castUpdateVal(schematype, val, op, key, context, prefix + key);
  159. } catch (error) {
  160. aggregatedError = _handleCastError(error, context, key, aggregatedError);
  161. }
  162. if (options.omitUndefined && obj[key] === void 0) {
  163. delete obj[key];
  164. continue;
  165. }
  166. hasKeys = true;
  167. } else {
  168. const pathToCheck = (prefix + key);
  169. const v = schema._getPathType(pathToCheck);
  170. let _strict = strict;
  171. if (useNestedStrict &&
  172. v &&
  173. v.schema &&
  174. 'strict' in v.schema.options) {
  175. _strict = v.schema.options.strict;
  176. }
  177. if (v.pathType === 'undefined') {
  178. if (_strict === 'throw') {
  179. throw new StrictModeError(pathToCheck);
  180. } else if (_strict) {
  181. delete obj[key];
  182. continue;
  183. }
  184. }
  185. // gh-2314
  186. // we should be able to set a schema-less field
  187. // to an empty object literal
  188. hasKeys |= walkUpdatePath(schema, val, op, options, context, filter, prefix + key) ||
  189. (utils.isObject(val) && Object.keys(val).length === 0);
  190. }
  191. } else {
  192. const checkPath = (key === '$each' || key === '$or' || key === '$and' || key === '$in') ?
  193. pref : prefix + key;
  194. schematype = schema._getSchema(checkPath);
  195. let pathDetails = schema._getPathType(checkPath);
  196. // If no schema type, check for embedded discriminators
  197. if (schematype == null) {
  198. const _res = getEmbeddedDiscriminatorPath(schema, obj, filter, checkPath);
  199. if (_res.schematype != null) {
  200. schematype = _res.schematype;
  201. pathDetails = _res.type;
  202. }
  203. }
  204. let isStrict = strict;
  205. if (useNestedStrict &&
  206. pathDetails &&
  207. pathDetails.schema &&
  208. 'strict' in pathDetails.schema.options) {
  209. isStrict = pathDetails.schema.options.strict;
  210. }
  211. const skip = isStrict &&
  212. !schematype &&
  213. !/real|nested/.test(pathDetails.pathType);
  214. if (skip) {
  215. // Even if strict is `throw`, avoid throwing an error because of
  216. // virtuals because of #6731
  217. if (isStrict === 'throw' && schema.virtuals[checkPath] == null) {
  218. throw new StrictModeError(prefix + key);
  219. } else {
  220. delete obj[key];
  221. }
  222. } else {
  223. // gh-1845 temporary fix: ignore $rename. See gh-3027 for tracking
  224. // improving this.
  225. if (op === '$rename') {
  226. hasKeys = true;
  227. continue;
  228. }
  229. try {
  230. obj[key] = castUpdateVal(schematype, val, op, key, context, prefix + key);
  231. } catch (error) {
  232. aggregatedError = _handleCastError(error, context, key, aggregatedError);
  233. }
  234. if (Array.isArray(obj[key]) && (op === '$addToSet' || op === '$push') && key !== '$each') {
  235. if (schematype && schematype.caster && !schematype.caster.$isMongooseArray) {
  236. obj[key] = { $each: obj[key] };
  237. }
  238. }
  239. if (options.omitUndefined && obj[key] === void 0) {
  240. delete obj[key];
  241. continue;
  242. }
  243. hasKeys = true;
  244. }
  245. }
  246. }
  247. if (aggregatedError != null) {
  248. throw aggregatedError;
  249. }
  250. return hasKeys;
  251. }
  252. /*!
  253. * ignore
  254. */
  255. function _handleCastError(error, query, key, aggregatedError) {
  256. if (typeof query !== 'object' || !query.options.multipleCastError) {
  257. throw error;
  258. }
  259. aggregatedError = aggregatedError || new ValidationError();
  260. aggregatedError.addError(key, error);
  261. return aggregatedError;
  262. }
  263. /*!
  264. * These operators should be cast to numbers instead
  265. * of their path schema type.
  266. */
  267. const numberOps = {
  268. $pop: 1,
  269. $inc: 1
  270. };
  271. /*!
  272. * These ops require no casting because the RHS doesn't do anything.
  273. */
  274. const noCastOps = {
  275. $unset: 1
  276. };
  277. /*!
  278. * These operators require casting docs
  279. * to real Documents for Update operations.
  280. */
  281. const castOps = {
  282. $push: 1,
  283. $addToSet: 1,
  284. $set: 1,
  285. $setOnInsert: 1
  286. };
  287. /*!
  288. * ignore
  289. */
  290. const overwriteOps = {
  291. $set: 1,
  292. $setOnInsert: 1
  293. };
  294. /*!
  295. * Casts `val` according to `schema` and atomic `op`.
  296. *
  297. * @param {SchemaType} schema
  298. * @param {Object} val
  299. * @param {String} op - the atomic operator ($pull, $set, etc)
  300. * @param {String} $conditional
  301. * @param {Query} context
  302. * @api private
  303. */
  304. function castUpdateVal(schema, val, op, $conditional, context, path) {
  305. if (!schema) {
  306. // non-existing schema path
  307. if (op in numberOps) {
  308. try {
  309. return castNumber(val);
  310. } catch (err) {
  311. throw new CastError('number', val, path);
  312. }
  313. }
  314. return val;
  315. }
  316. const cond = schema.caster && op in castOps &&
  317. (utils.isObject(val) || Array.isArray(val));
  318. if (cond && !overwriteOps[op]) {
  319. // Cast values for ops that add data to MongoDB.
  320. // Ensures embedded documents get ObjectIds etc.
  321. let schemaArrayDepth = 0;
  322. let cur = schema;
  323. while (cur.$isMongooseArray) {
  324. ++schemaArrayDepth;
  325. cur = cur.caster;
  326. }
  327. let arrayDepth = 0;
  328. let _val = val;
  329. while (Array.isArray(_val)) {
  330. ++arrayDepth;
  331. _val = _val[0];
  332. }
  333. const additionalNesting = schemaArrayDepth - arrayDepth;
  334. while (arrayDepth < schemaArrayDepth) {
  335. val = [val];
  336. ++arrayDepth;
  337. }
  338. let tmp = schema.cast(Array.isArray(val) ? val : [val]);
  339. for (let i = 0; i < additionalNesting; ++i) {
  340. tmp = tmp[0];
  341. }
  342. return tmp;
  343. }
  344. if (op in noCastOps) {
  345. return val;
  346. }
  347. if (op in numberOps) {
  348. // Null and undefined not allowed for $pop, $inc
  349. if (val == null) {
  350. throw new CastError('number', val, schema.path);
  351. }
  352. if (op === '$inc') {
  353. // Support `$inc` with long, int32, etc. (gh-4283)
  354. return schema.castForQueryWrapper({
  355. val: val,
  356. context: context
  357. });
  358. }
  359. try {
  360. return castNumber(val);
  361. } catch (error) {
  362. throw new CastError('number', val, schema.path);
  363. }
  364. }
  365. if (op === '$currentDate') {
  366. if (typeof val === 'object') {
  367. return {$type: val.$type};
  368. }
  369. return Boolean(val);
  370. }
  371. if (/^\$/.test($conditional)) {
  372. return schema.castForQueryWrapper({
  373. $conditional: $conditional,
  374. val: val,
  375. context: context
  376. });
  377. }
  378. if (overwriteOps[op]) {
  379. return schema.castForQueryWrapper({
  380. val: val,
  381. context: context,
  382. $skipQueryCastForUpdate: val != null && schema.$isMongooseArray && schema.$fullPath != null && !schema.$fullPath.match(/\d+$/)
  383. });
  384. }
  385. return schema.castForQueryWrapper({ val: val, context: context });
  386. }