cast.js 12 KB

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