castUpdate.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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) {
  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. while (i--) {
  166. key = keys[i];
  167. val = obj[key];
  168. // `$pull` is special because we need to cast the RHS as a query, not as
  169. // an update.
  170. if (op === '$pull') {
  171. schematype = schema._getSchema(prefix + key);
  172. if (schematype != null && schematype.schema != null) {
  173. obj[key] = cast(schematype.schema, obj[key], options, context);
  174. hasKeys = true;
  175. continue;
  176. }
  177. }
  178. if (getConstructorName(val) === 'Object') {
  179. // watch for embedded doc schemas
  180. schematype = schema._getSchema(prefix + key);
  181. if (schematype == null) {
  182. const _res = getEmbeddedDiscriminatorPath(schema, obj, filter, prefix + key, options);
  183. if (_res.schematype != null) {
  184. schematype = _res.schematype;
  185. }
  186. }
  187. if (op !== '$setOnInsert' &&
  188. handleImmutable(schematype, strict, obj, key, prefix + key, context)) {
  189. continue;
  190. }
  191. if (schematype && schematype.caster && op in castOps) {
  192. // embedded doc schema
  193. if ('$each' in val) {
  194. hasKeys = true;
  195. try {
  196. obj[key] = {
  197. $each: castUpdateVal(schematype, val.$each, op, key, context, prefix + key)
  198. };
  199. } catch (error) {
  200. aggregatedError = _handleCastError(error, context, key, aggregatedError);
  201. }
  202. if (val.$slice != null) {
  203. obj[key].$slice = val.$slice | 0;
  204. }
  205. if (val.$sort) {
  206. obj[key].$sort = val.$sort;
  207. }
  208. if (val.$position != null) {
  209. obj[key].$position = castNumber(val.$position);
  210. }
  211. } else {
  212. if (schematype != null && schematype.$isSingleNested) {
  213. const _strict = strict == null ? schematype.schema.options.strict : strict;
  214. try {
  215. obj[key] = schematype.castForQuery(val, context, { strict: _strict });
  216. } catch (error) {
  217. aggregatedError = _handleCastError(error, context, key, aggregatedError);
  218. }
  219. } else {
  220. try {
  221. obj[key] = castUpdateVal(schematype, val, op, key, context, prefix + key);
  222. } catch (error) {
  223. aggregatedError = _handleCastError(error, context, key, aggregatedError);
  224. }
  225. }
  226. if (obj[key] === void 0) {
  227. delete obj[key];
  228. continue;
  229. }
  230. hasKeys = true;
  231. }
  232. } else if ((op === '$currentDate') || (op in castOps && schematype)) {
  233. // $currentDate can take an object
  234. try {
  235. obj[key] = castUpdateVal(schematype, val, op, key, context, prefix + key);
  236. } catch (error) {
  237. aggregatedError = _handleCastError(error, context, key, aggregatedError);
  238. }
  239. if (obj[key] === void 0) {
  240. delete obj[key];
  241. continue;
  242. }
  243. hasKeys = true;
  244. } else {
  245. const pathToCheck = (prefix + key);
  246. const v = schema._getPathType(pathToCheck);
  247. let _strict = strict;
  248. if (v && v.schema && _strict == null) {
  249. _strict = v.schema.options.strict;
  250. }
  251. if (v.pathType === 'undefined') {
  252. if (_strict === 'throw') {
  253. throw new StrictModeError(pathToCheck);
  254. } else if (_strict) {
  255. delete obj[key];
  256. continue;
  257. }
  258. }
  259. // gh-2314
  260. // we should be able to set a schema-less field
  261. // to an empty object literal
  262. hasKeys |= walkUpdatePath(schema, val, op, options, context, filter, prefix + key) ||
  263. (utils.isObject(val) && Object.keys(val).length === 0);
  264. }
  265. } else {
  266. const checkPath = (key === '$each' || key === '$or' || key === '$and' || key === '$in') ?
  267. pref : prefix + key;
  268. schematype = schema._getSchema(checkPath);
  269. // You can use `$setOnInsert` with immutable keys
  270. if (op !== '$setOnInsert' &&
  271. handleImmutable(schematype, strict, obj, key, prefix + key, context)) {
  272. continue;
  273. }
  274. let pathDetails = schema._getPathType(checkPath);
  275. // If no schema type, check for embedded discriminators because the
  276. // filter or update may imply an embedded discriminator type. See #8378
  277. if (schematype == null) {
  278. const _res = getEmbeddedDiscriminatorPath(schema, obj, filter, checkPath, options);
  279. if (_res.schematype != null) {
  280. schematype = _res.schematype;
  281. pathDetails = _res.type;
  282. }
  283. }
  284. let isStrict = strict;
  285. if (pathDetails && pathDetails.schema && strict == null) {
  286. isStrict = pathDetails.schema.options.strict;
  287. }
  288. const skip = isStrict &&
  289. !schematype &&
  290. !/real|nested/.test(pathDetails.pathType);
  291. if (skip) {
  292. // Even if strict is `throw`, avoid throwing an error because of
  293. // virtuals because of #6731
  294. if (isStrict === 'throw' && schema.virtuals[checkPath] == null) {
  295. throw new StrictModeError(prefix + key);
  296. } else {
  297. delete obj[key];
  298. }
  299. } else {
  300. // gh-1845 temporary fix: ignore $rename. See gh-3027 for tracking
  301. // improving this.
  302. if (op === '$rename') {
  303. hasKeys = true;
  304. continue;
  305. }
  306. try {
  307. if (prefix.length === 0 || key.indexOf('.') === -1) {
  308. obj[key] = castUpdateVal(schematype, val, op, key, context, prefix + key);
  309. } else {
  310. // Setting a nested dotted path that's in the schema. We don't allow paths with '.' in
  311. // a schema, so replace the dotted path with a nested object to avoid ending up with
  312. // dotted properties in the updated object. See (gh-10200)
  313. setDottedPath(obj, key, castUpdateVal(schematype, val, op, key, context, prefix + key));
  314. delete obj[key];
  315. }
  316. } catch (error) {
  317. aggregatedError = _handleCastError(error, context, key, aggregatedError);
  318. }
  319. if (Array.isArray(obj[key]) && (op === '$addToSet' || op === '$push') && key !== '$each') {
  320. if (schematype &&
  321. schematype.caster &&
  322. !schematype.caster.$isMongooseArray &&
  323. !schematype.caster[schemaMixedSymbol]) {
  324. obj[key] = { $each: obj[key] };
  325. }
  326. }
  327. if (obj[key] === void 0) {
  328. delete obj[key];
  329. continue;
  330. }
  331. hasKeys = true;
  332. }
  333. }
  334. }
  335. if (aggregatedError != null) {
  336. throw aggregatedError;
  337. }
  338. return hasKeys;
  339. }
  340. /*!
  341. * ignore
  342. */
  343. function _handleCastError(error, query, key, aggregatedError) {
  344. if (typeof query !== 'object' || !query.options.multipleCastError) {
  345. throw error;
  346. }
  347. aggregatedError = aggregatedError || new ValidationError();
  348. aggregatedError.addError(key, error);
  349. return aggregatedError;
  350. }
  351. /*!
  352. * These operators should be cast to numbers instead
  353. * of their path schema type.
  354. */
  355. const numberOps = {
  356. $pop: 1,
  357. $inc: 1
  358. };
  359. /*!
  360. * These ops require no casting because the RHS doesn't do anything.
  361. */
  362. const noCastOps = {
  363. $unset: 1
  364. };
  365. /*!
  366. * These operators require casting docs
  367. * to real Documents for Update operations.
  368. */
  369. const castOps = {
  370. $push: 1,
  371. $addToSet: 1,
  372. $set: 1,
  373. $setOnInsert: 1
  374. };
  375. /*!
  376. * ignore
  377. */
  378. const overwriteOps = {
  379. $set: 1,
  380. $setOnInsert: 1
  381. };
  382. /*!
  383. * Casts `val` according to `schema` and atomic `op`.
  384. *
  385. * @param {SchemaType} schema
  386. * @param {Object} val
  387. * @param {String} op - the atomic operator ($pull, $set, etc)
  388. * @param {String} $conditional
  389. * @param {Query} context
  390. * @api private
  391. */
  392. function castUpdateVal(schema, val, op, $conditional, context, path) {
  393. if (!schema) {
  394. // non-existing schema path
  395. if (op in numberOps) {
  396. try {
  397. return castNumber(val);
  398. } catch (err) {
  399. throw new CastError('number', val, path);
  400. }
  401. }
  402. return val;
  403. }
  404. const cond = schema.caster && op in castOps &&
  405. (utils.isObject(val) || Array.isArray(val));
  406. if (cond && !overwriteOps[op]) {
  407. // Cast values for ops that add data to MongoDB.
  408. // Ensures embedded documents get ObjectIds etc.
  409. let schemaArrayDepth = 0;
  410. let cur = schema;
  411. while (cur.$isMongooseArray) {
  412. ++schemaArrayDepth;
  413. cur = cur.caster;
  414. }
  415. let arrayDepth = 0;
  416. let _val = val;
  417. while (Array.isArray(_val)) {
  418. ++arrayDepth;
  419. _val = _val[0];
  420. }
  421. const additionalNesting = schemaArrayDepth - arrayDepth;
  422. while (arrayDepth < schemaArrayDepth) {
  423. val = [val];
  424. ++arrayDepth;
  425. }
  426. let tmp = schema.applySetters(Array.isArray(val) ? val : [val], context);
  427. for (let i = 0; i < additionalNesting; ++i) {
  428. tmp = tmp[0];
  429. }
  430. return tmp;
  431. }
  432. if (op in noCastOps) {
  433. return val;
  434. }
  435. if (op in numberOps) {
  436. // Null and undefined not allowed for $pop, $inc
  437. if (val == null) {
  438. throw new CastError('number', val, schema.path);
  439. }
  440. if (op === '$inc') {
  441. // Support `$inc` with long, int32, etc. (gh-4283)
  442. return schema.castForQueryWrapper({
  443. val: val,
  444. context: context
  445. });
  446. }
  447. try {
  448. return castNumber(val);
  449. } catch (error) {
  450. throw new CastError('number', val, schema.path);
  451. }
  452. }
  453. if (op === '$currentDate') {
  454. if (typeof val === 'object') {
  455. return { $type: val.$type };
  456. }
  457. return Boolean(val);
  458. }
  459. if (/^\$/.test($conditional)) {
  460. return schema.castForQueryWrapper({
  461. $conditional: $conditional,
  462. val: val,
  463. context: context
  464. });
  465. }
  466. if (overwriteOps[op]) {
  467. return schema.castForQueryWrapper({
  468. val: val,
  469. context: context,
  470. $skipQueryCastForUpdate: val != null && schema.$isMongooseArray && schema.$fullPath != null && !schema.$fullPath.match(/\d+$/),
  471. $applySetters: schema[schemaMixedSymbol] != null
  472. });
  473. }
  474. return schema.castForQueryWrapper({ val: val, context: context });
  475. }