cast.js 12 KB

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