castUpdate.js 16 KB

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