cast.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. 'use strict';
  2. /*!
  3. * Module dependencies.
  4. */
  5. const CastError = require('./error/cast');
  6. const StrictModeError = require('./error/strict');
  7. const Types = require('./schema/index');
  8. const cast$expr = require('./helpers/query/cast$expr');
  9. const castString = require('./cast/string');
  10. const castTextSearch = require('./schema/operators/text');
  11. const get = require('./helpers/get');
  12. const getSchemaDiscriminatorByValue = require('./helpers/discriminator/getSchemaDiscriminatorByValue');
  13. const isOperator = require('./helpers/query/isOperator');
  14. const util = require('util');
  15. const isObject = require('./helpers/isObject');
  16. const isMongooseObject = require('./helpers/isMongooseObject');
  17. const utils = require('./utils');
  18. const ALLOWED_GEOWITHIN_GEOJSON_TYPES = ['Polygon', 'MultiPolygon'];
  19. /**
  20. * Handles internal casting for query filters.
  21. *
  22. * @param {Schema} schema
  23. * @param {Object} obj Object to cast
  24. * @param {Object} [options] the query options
  25. * @param {Boolean|"throw"} [options.strict] Wheter to enable all strict options
  26. * @param {Boolean|"throw"} [options.strictQuery] Enable strict Queries
  27. * @param {Boolean} [options.sanitizeFilter] avoid adding implict query selectors ($in)
  28. * @param {Boolean} [options.upsert]
  29. * @param {Query} [context] passed to setters
  30. * @api private
  31. */
  32. module.exports = function cast(schema, obj, options, context) {
  33. if (Array.isArray(obj)) {
  34. throw new Error('Query filter must be an object, got an array ', util.inspect(obj));
  35. }
  36. if (obj == null) {
  37. return obj;
  38. }
  39. if (schema?.discriminators != null && obj[schema.options.discriminatorKey] != null) {
  40. schema = getSchemaDiscriminatorByValue(schema, obj[schema.options.discriminatorKey]) || schema;
  41. }
  42. const paths = Object.keys(obj);
  43. let i = paths.length;
  44. let _keys;
  45. let any$conditionals;
  46. let schematype;
  47. let nested;
  48. let path;
  49. let type;
  50. let val;
  51. options = options || {};
  52. while (i--) {
  53. path = paths[i];
  54. val = obj[path];
  55. if (path === '$or' || path === '$nor' || path === '$and') {
  56. if (!Array.isArray(val)) {
  57. throw new CastError('Array', val, path);
  58. }
  59. for (let k = val.length - 1; k >= 0; k--) {
  60. if (val[k] == null || typeof val[k] !== 'object') {
  61. throw new CastError('Object', val[k], path + '.' + k);
  62. }
  63. const beforeCastKeysLength = Object.keys(val[k]).length;
  64. const discriminatorValue = val[k][schema.options.discriminatorKey];
  65. if (discriminatorValue == null) {
  66. val[k] = cast(schema, val[k], options, context);
  67. } else {
  68. const discriminatorSchema = getSchemaDiscriminatorByValue(context.schema, discriminatorValue);
  69. val[k] = cast(discriminatorSchema ? discriminatorSchema : schema, val[k], options, context);
  70. }
  71. if (utils.hasOwnKeys(val[k]) === false && beforeCastKeysLength !== 0) {
  72. val.splice(k, 1);
  73. }
  74. }
  75. // delete empty: {$or: []} -> {}
  76. if (val.length === 0) {
  77. delete obj[path];
  78. }
  79. } else if (path === '$where') {
  80. type = typeof val;
  81. if (type !== 'string' && type !== 'function') {
  82. throw new Error('Must have a string or function for $where');
  83. }
  84. if (type === 'function') {
  85. obj[path] = val.toString();
  86. }
  87. continue;
  88. } else if (path === '$expr') {
  89. val = cast$expr(val, schema);
  90. continue;
  91. } else if (path === '$elemMatch') {
  92. val = cast(schema, val, options, context);
  93. } else if (path === '$text') {
  94. val = castTextSearch(val, path);
  95. } else if (path === '$comment' && !Object.hasOwn(schema.paths, '$comment')) {
  96. val = castString(val, path);
  97. obj[path] = val;
  98. } else {
  99. if (!schema) {
  100. // no casting for Mixed types
  101. continue;
  102. }
  103. schematype = schema.path(path);
  104. // Check for embedded discriminator paths
  105. if (!schematype) {
  106. const split = path.split('.');
  107. let j = split.length;
  108. while (j--) {
  109. const pathFirstHalf = split.slice(0, j).join('.');
  110. const pathLastHalf = split.slice(j).join('.');
  111. const _schematype = schema.path(pathFirstHalf);
  112. const discriminatorKey = _schematype?.schema?.options?.discriminatorKey;
  113. // gh-6027: if we haven't found the schematype but this path is
  114. // underneath an embedded discriminator and the embedded discriminator
  115. // key is in the query, use the embedded discriminator schema
  116. if (_schematype?.schema?.discriminators != null &&
  117. discriminatorKey != null &&
  118. pathLastHalf !== discriminatorKey) {
  119. const discriminatorVal = get(obj, pathFirstHalf + '.' + discriminatorKey);
  120. const discriminators = _schematype.schema.discriminators;
  121. if (typeof discriminatorVal === 'string' && discriminators[discriminatorVal] != null) {
  122. schematype = discriminators[discriminatorVal].path(pathLastHalf);
  123. } else if (discriminatorVal != null &&
  124. Object.keys(discriminatorVal).length === 1 &&
  125. Array.isArray(discriminatorVal.$in) &&
  126. discriminatorVal.$in.length === 1 &&
  127. typeof discriminatorVal.$in[0] === 'string' &&
  128. discriminators[discriminatorVal.$in[0]] != null) {
  129. schematype = discriminators[discriminatorVal.$in[0]].path(pathLastHalf);
  130. }
  131. }
  132. }
  133. }
  134. if (!schematype) {
  135. // Handle potential embedded array queries
  136. const split = path.split('.');
  137. let j = split.length;
  138. let pathFirstHalf;
  139. let pathLastHalf;
  140. let remainingConds;
  141. // Find the part of the var path that is a path of the Schema
  142. while (j--) {
  143. pathFirstHalf = split.slice(0, j).join('.');
  144. schematype = schema.path(pathFirstHalf);
  145. if (schematype) {
  146. break;
  147. }
  148. }
  149. // If a substring of the input path resolves to an actual real path...
  150. if (schematype) {
  151. // Apply the casting; similar code for $elemMatch in schema/array.js
  152. if (schematype.schema) {
  153. remainingConds = {};
  154. pathLastHalf = split.slice(j).join('.');
  155. remainingConds[pathLastHalf] = val;
  156. const ret = cast(schematype.schema, remainingConds, options, context)[pathLastHalf];
  157. if (ret === void 0) {
  158. delete obj[path];
  159. } else {
  160. obj[path] = ret;
  161. }
  162. } else {
  163. obj[path] = val;
  164. }
  165. continue;
  166. }
  167. if (isObject(val)) {
  168. // handle geo schemas that use object notation
  169. // { loc: { long: Number, lat: Number }
  170. let geo = '';
  171. if (val.$near) {
  172. geo = '$near';
  173. } else if (val.$nearSphere) {
  174. geo = '$nearSphere';
  175. } else if (val.$within) {
  176. geo = '$within';
  177. } else if (val.$geoIntersects) {
  178. geo = '$geoIntersects';
  179. } else if (val.$geoWithin) {
  180. geo = '$geoWithin';
  181. }
  182. if (geo) {
  183. const numbertype = new Types.Number('__QueryCasting__', null, null, schema);
  184. let value = val[geo];
  185. if (val.$maxDistance != null) {
  186. val.$maxDistance = numbertype.castForQuery(
  187. null,
  188. val.$maxDistance,
  189. context
  190. );
  191. }
  192. if (val.$minDistance != null) {
  193. val.$minDistance = numbertype.castForQuery(
  194. null,
  195. val.$minDistance,
  196. context
  197. );
  198. }
  199. if (geo === '$within') {
  200. const withinType = value.$center
  201. || value.$centerSphere
  202. || value.$box
  203. || value.$polygon;
  204. if (!withinType) {
  205. throw new Error('Bad $within parameter: ' + JSON.stringify(val));
  206. }
  207. value = withinType;
  208. } else if (geo === '$near' &&
  209. typeof value.type === 'string' && Array.isArray(value.coordinates)) {
  210. // geojson; cast the coordinates
  211. value = value.coordinates;
  212. } else if ((geo === '$near' || geo === '$nearSphere' || geo === '$geoIntersects') &&
  213. value.$geometry && typeof value.$geometry.type === 'string' &&
  214. Array.isArray(value.$geometry.coordinates)) {
  215. if (value.$maxDistance != null) {
  216. value.$maxDistance = numbertype.castForQuery(
  217. null,
  218. value.$maxDistance,
  219. context
  220. );
  221. }
  222. if (value.$minDistance != null) {
  223. value.$minDistance = numbertype.castForQuery(
  224. null,
  225. value.$minDistance,
  226. context
  227. );
  228. }
  229. if (isMongooseObject(value.$geometry)) {
  230. value.$geometry = value.$geometry.toObject({
  231. transform: false,
  232. virtuals: false
  233. });
  234. }
  235. value = value.$geometry.coordinates;
  236. } else if (geo === '$geoWithin') {
  237. if (value.$geometry) {
  238. if (isMongooseObject(value.$geometry)) {
  239. value.$geometry = value.$geometry.toObject({ virtuals: false });
  240. }
  241. const geoWithinType = value.$geometry.type;
  242. if (ALLOWED_GEOWITHIN_GEOJSON_TYPES.indexOf(geoWithinType) === -1) {
  243. throw new Error('Invalid geoJSON type for $geoWithin "' +
  244. geoWithinType + '", must be "Polygon" or "MultiPolygon"');
  245. }
  246. value = value.$geometry.coordinates;
  247. } else {
  248. value = value.$box || value.$polygon || value.$center ||
  249. value.$centerSphere;
  250. if (isMongooseObject(value)) {
  251. value = value.toObject({ virtuals: false });
  252. }
  253. }
  254. }
  255. _cast(value, numbertype, context);
  256. continue;
  257. }
  258. }
  259. if (schema.nested[path]) {
  260. continue;
  261. }
  262. const strict = 'strict' in options ? options.strict : schema.options.strict;
  263. const strictQuery = getStrictQuery(options, schema._userProvidedOptions, schema.options, context);
  264. if (options.upsert && strict) {
  265. if (strict === 'throw') {
  266. throw new StrictModeError(path);
  267. }
  268. throw new StrictModeError(path, 'Path "' + path + '" is not in ' +
  269. 'schema, strict mode is `true`, and upsert is `true`.');
  270. } if (strictQuery === 'throw') {
  271. throw new StrictModeError(path, 'Path "' + path + '" is not in ' +
  272. 'schema and strictQuery is \'throw\'.');
  273. } else if (strictQuery) {
  274. delete obj[path];
  275. }
  276. } else if (val == null) {
  277. continue;
  278. } else if (utils.isPOJO(val)) {
  279. any$conditionals = Object.keys(val).some(isOperator);
  280. if (!any$conditionals) {
  281. obj[path] = schematype.castForQuery(
  282. null,
  283. val,
  284. context
  285. );
  286. } else {
  287. const ks = Object.keys(val);
  288. let $cond;
  289. let k = ks.length;
  290. while (k--) {
  291. $cond = ks[k];
  292. nested = val[$cond];
  293. if ($cond === '$elemMatch') {
  294. if (nested && schematype?.schema != null) {
  295. cast(schematype.schema, nested, options, context);
  296. } else if (nested && schematype?.$isMongooseArray) {
  297. if (utils.isPOJO(nested) && nested.$not != null) {
  298. cast(schema, nested, options, context);
  299. } else {
  300. val[$cond] = schematype.castForQuery(
  301. $cond,
  302. nested,
  303. context
  304. );
  305. }
  306. }
  307. } else if ($cond === '$not') {
  308. if (nested && schematype) {
  309. _keys = Object.keys(nested);
  310. if (_keys.length && isOperator(_keys[0])) {
  311. for (const key in nested) {
  312. nested[key] = schematype.castForQuery(
  313. key,
  314. nested[key],
  315. context
  316. );
  317. }
  318. } else {
  319. val[$cond] = schematype.castForQuery(
  320. $cond,
  321. nested,
  322. context
  323. );
  324. }
  325. continue;
  326. }
  327. } else {
  328. val[$cond] = schematype.castForQuery(
  329. $cond,
  330. nested,
  331. context
  332. );
  333. }
  334. }
  335. }
  336. } else if (Array.isArray(val) && ['Buffer', 'Array'].indexOf(schematype.instance) === -1 && !options.sanitizeFilter) {
  337. const casted = [];
  338. const valuesArray = val;
  339. for (const _val of valuesArray) {
  340. casted.push(schematype.castForQuery(
  341. null,
  342. _val,
  343. context
  344. ));
  345. }
  346. obj[path] = { $in: casted };
  347. } else {
  348. obj[path] = schematype.castForQuery(
  349. null,
  350. val,
  351. context
  352. );
  353. }
  354. }
  355. }
  356. return obj;
  357. };
  358. function _cast(val, numbertype, context) {
  359. if (Array.isArray(val)) {
  360. val.forEach(function(item, i) {
  361. if (Array.isArray(item) || isObject(item)) {
  362. return _cast(item, numbertype, context);
  363. }
  364. val[i] = numbertype.castForQuery(null, item, context);
  365. });
  366. } else {
  367. const nearKeys = Object.keys(val);
  368. let nearLen = nearKeys.length;
  369. while (nearLen--) {
  370. const nkey = nearKeys[nearLen];
  371. const item = val[nkey];
  372. if (Array.isArray(item) || isObject(item)) {
  373. _cast(item, numbertype, context);
  374. val[nkey] = item;
  375. } else {
  376. val[nkey] = numbertype.castForQuery({ val: item, context: context });
  377. }
  378. }
  379. }
  380. }
  381. function getStrictQuery(queryOptions, schemaUserProvidedOptions, schemaOptions, context) {
  382. if ('strictQuery' in queryOptions) {
  383. return queryOptions.strictQuery;
  384. }
  385. if ('strictQuery' in schemaUserProvidedOptions) {
  386. return schemaUserProvidedOptions.strictQuery;
  387. }
  388. const mongooseOptions = context?.mongooseCollection?.conn?.base?.options;
  389. if (mongooseOptions) {
  390. if ('strictQuery' in mongooseOptions) {
  391. return mongooseOptions.strictQuery;
  392. }
  393. }
  394. return schemaOptions.strictQuery;
  395. }