castUpdate.js 15 KB

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