cast.js 12 KB

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