cast.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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 = get(_schematype, 'schema.options.discriminatorKey');
  91. // gh-6027: if we haven't found the schematype but this path is
  92. // underneath an embedded discriminator and the embedded discriminator
  93. // key is in the query, use the embedded discriminator schema
  94. if (_schematype != null &&
  95. get(_schematype, 'schema.discriminators') != null &&
  96. discriminatorKey != null &&
  97. pathLastHalf !== discriminatorKey) {
  98. const discriminatorVal = get(obj, pathFirstHalf + '.' + discriminatorKey);
  99. if (discriminatorVal != null) {
  100. schematype = _schematype.schema.discriminators[discriminatorVal].
  101. path(pathLastHalf);
  102. }
  103. }
  104. }
  105. }
  106. if (!schematype) {
  107. // Handle potential embedded array queries
  108. const split = path.split('.');
  109. let j = split.length;
  110. let pathFirstHalf;
  111. let pathLastHalf;
  112. let remainingConds;
  113. // Find the part of the var path that is a path of the Schema
  114. while (j--) {
  115. pathFirstHalf = split.slice(0, j).join('.');
  116. schematype = schema.path(pathFirstHalf);
  117. if (schematype) {
  118. break;
  119. }
  120. }
  121. // If a substring of the input path resolves to an actual real path...
  122. if (schematype) {
  123. // Apply the casting; similar code for $elemMatch in schema/array.js
  124. if (schematype.caster && schematype.caster.schema) {
  125. remainingConds = {};
  126. pathLastHalf = split.slice(j).join('.');
  127. remainingConds[pathLastHalf] = val;
  128. const ret = cast(schematype.caster.schema, remainingConds, options, context)[pathLastHalf];
  129. if (ret === void 0) {
  130. delete obj[path];
  131. } else {
  132. obj[path] = ret;
  133. }
  134. } else {
  135. obj[path] = val;
  136. }
  137. continue;
  138. }
  139. if (isObject(val)) {
  140. // handle geo schemas that use object notation
  141. // { loc: { long: Number, lat: Number }
  142. let geo = '';
  143. if (val.$near) {
  144. geo = '$near';
  145. } else if (val.$nearSphere) {
  146. geo = '$nearSphere';
  147. } else if (val.$within) {
  148. geo = '$within';
  149. } else if (val.$geoIntersects) {
  150. geo = '$geoIntersects';
  151. } else if (val.$geoWithin) {
  152. geo = '$geoWithin';
  153. }
  154. if (geo) {
  155. const numbertype = new Types.Number('__QueryCasting__');
  156. let value = val[geo];
  157. if (val.$maxDistance != null) {
  158. val.$maxDistance = numbertype.castForQueryWrapper({
  159. val: val.$maxDistance,
  160. context: context
  161. });
  162. }
  163. if (val.$minDistance != null) {
  164. val.$minDistance = numbertype.castForQueryWrapper({
  165. val: val.$minDistance,
  166. context: context
  167. });
  168. }
  169. if (geo === '$within') {
  170. const withinType = value.$center
  171. || value.$centerSphere
  172. || value.$box
  173. || value.$polygon;
  174. if (!withinType) {
  175. throw new Error('Bad $within parameter: ' + JSON.stringify(val));
  176. }
  177. value = withinType;
  178. } else if (geo === '$near' &&
  179. typeof value.type === 'string' && Array.isArray(value.coordinates)) {
  180. // geojson; cast the coordinates
  181. value = value.coordinates;
  182. } else if ((geo === '$near' || geo === '$nearSphere' || geo === '$geoIntersects') &&
  183. value.$geometry && typeof value.$geometry.type === 'string' &&
  184. Array.isArray(value.$geometry.coordinates)) {
  185. if (value.$maxDistance != null) {
  186. value.$maxDistance = numbertype.castForQueryWrapper({
  187. val: value.$maxDistance,
  188. context: context
  189. });
  190. }
  191. if (value.$minDistance != null) {
  192. value.$minDistance = numbertype.castForQueryWrapper({
  193. val: value.$minDistance,
  194. context: context
  195. });
  196. }
  197. if (isMongooseObject(value.$geometry)) {
  198. value.$geometry = value.$geometry.toObject({
  199. transform: false,
  200. virtuals: false
  201. });
  202. }
  203. value = value.$geometry.coordinates;
  204. } else if (geo === '$geoWithin') {
  205. if (value.$geometry) {
  206. if (isMongooseObject(value.$geometry)) {
  207. value.$geometry = value.$geometry.toObject({ virtuals: false });
  208. }
  209. const geoWithinType = value.$geometry.type;
  210. if (ALLOWED_GEOWITHIN_GEOJSON_TYPES.indexOf(geoWithinType) === -1) {
  211. throw new Error('Invalid geoJSON type for $geoWithin "' +
  212. geoWithinType + '", must be "Polygon" or "MultiPolygon"');
  213. }
  214. value = value.$geometry.coordinates;
  215. } else {
  216. value = value.$box || value.$polygon || value.$center ||
  217. value.$centerSphere;
  218. if (isMongooseObject(value)) {
  219. value = value.toObject({ virtuals: false });
  220. }
  221. }
  222. }
  223. _cast(value, numbertype, context);
  224. continue;
  225. }
  226. }
  227. if (schema.nested[path]) {
  228. continue;
  229. }
  230. const strict = 'strict' in options ? options.strict : schema.options.strict;
  231. const strictQuery = 'strictQuery' in options ?
  232. options.strictQuery :
  233. 'strict' in options ?
  234. options.strict :
  235. 'strict' in schema._userProvidedOptions ? schema._userProvidedOptions.strict :
  236. schema.options.strictQuery;
  237. if (options.upsert && strict) {
  238. if (strict === 'throw') {
  239. throw new StrictModeError(path);
  240. }
  241. throw new StrictModeError(path, 'Path "' + path + '" is not in ' +
  242. 'schema, strict mode is `true`, and upsert is `true`.');
  243. } if (strictQuery === 'throw') {
  244. throw new StrictModeError(path, 'Path "' + path + '" is not in ' +
  245. 'schema and strictQuery is \'throw\'.');
  246. } else if (strictQuery) {
  247. delete obj[path];
  248. }
  249. } else if (val == null) {
  250. continue;
  251. } else if (getConstructorName(val) === 'Object') {
  252. any$conditionals = Object.keys(val).some(isOperator);
  253. if (!any$conditionals) {
  254. obj[path] = schematype.castForQueryWrapper({
  255. val: val,
  256. context: context
  257. });
  258. } else {
  259. const ks = Object.keys(val);
  260. let $cond;
  261. let k = ks.length;
  262. while (k--) {
  263. $cond = ks[k];
  264. nested = val[$cond];
  265. if ($cond === '$not') {
  266. if (nested && schematype) {
  267. _keys = Object.keys(nested);
  268. if (_keys.length && isOperator(_keys[0])) {
  269. for (const key in nested) {
  270. nested[key] = schematype.castForQueryWrapper({
  271. $conditional: key,
  272. val: nested[key],
  273. context: context
  274. });
  275. }
  276. } else {
  277. val[$cond] = schematype.castForQueryWrapper({
  278. $conditional: $cond,
  279. val: nested,
  280. context: context
  281. });
  282. }
  283. continue;
  284. }
  285. } else {
  286. val[$cond] = schematype.castForQueryWrapper({
  287. $conditional: $cond,
  288. val: nested,
  289. context: context
  290. });
  291. }
  292. }
  293. }
  294. } else if (Array.isArray(val) && ['Buffer', 'Array'].indexOf(schematype.instance) === -1) {
  295. const casted = [];
  296. const valuesArray = val;
  297. for (const _val of valuesArray) {
  298. casted.push(schematype.castForQueryWrapper({
  299. val: _val,
  300. context: context
  301. }));
  302. }
  303. obj[path] = { $in: casted };
  304. } else {
  305. obj[path] = schematype.castForQueryWrapper({
  306. val: val,
  307. context: context
  308. });
  309. }
  310. }
  311. }
  312. return obj;
  313. };
  314. function _cast(val, numbertype, context) {
  315. if (Array.isArray(val)) {
  316. val.forEach(function(item, i) {
  317. if (Array.isArray(item) || isObject(item)) {
  318. return _cast(item, numbertype, context);
  319. }
  320. val[i] = numbertype.castForQueryWrapper({ val: item, context: context });
  321. });
  322. } else {
  323. const nearKeys = Object.keys(val);
  324. let nearLen = nearKeys.length;
  325. while (nearLen--) {
  326. const nkey = nearKeys[nearLen];
  327. const item = val[nkey];
  328. if (Array.isArray(item) || isObject(item)) {
  329. _cast(item, numbertype, context);
  330. val[nkey] = item;
  331. } else {
  332. val[nkey] = numbertype.castForQuery({ val: item, context: context });
  333. }
  334. }
  335. }
  336. }