castUpdate.js 14 KB

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