Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

castUpdate.js 12KB

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