SubdocumentPath.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. 'use strict';
  2. /*!
  3. * Module dependencies.
  4. */
  5. const CastError = require('../error/cast');
  6. const EventEmitter = require('events').EventEmitter;
  7. const ObjectExpectedError = require('../error/objectExpected');
  8. const SchemaSubdocumentOptions = require('../options/SchemaSubdocumentOptions');
  9. const SchemaType = require('../schematype');
  10. const $exists = require('./operators/exists');
  11. const castToNumber = require('./operators/helpers').castToNumber;
  12. const discriminator = require('../helpers/model/discriminator');
  13. const geospatial = require('./operators/geospatial');
  14. const getConstructor = require('../helpers/discriminator/getConstructor');
  15. const handleIdOption = require('../helpers/schema/handleIdOption');
  16. const internalToObjectOptions = require('../options').internalToObjectOptions;
  17. const utils = require('../utils');
  18. let Subdocument;
  19. module.exports = SubdocumentPath;
  20. /**
  21. * Single nested subdocument SchemaType constructor.
  22. *
  23. * @param {Schema} schema
  24. * @param {String} path
  25. * @param {Object} options
  26. * @inherits SchemaType
  27. * @api public
  28. */
  29. function SubdocumentPath(schema, path, options) {
  30. const schemaTypeIdOption = SubdocumentPath.defaultOptions &&
  31. SubdocumentPath.defaultOptions._id;
  32. if (schemaTypeIdOption != null) {
  33. options = options || {};
  34. options._id = schemaTypeIdOption;
  35. }
  36. schema = handleIdOption(schema, options);
  37. this.caster = _createConstructor(schema);
  38. this.caster.path = path;
  39. this.caster.prototype.$basePath = path;
  40. this.schema = schema;
  41. this.$isSingleNested = true;
  42. SchemaType.call(this, path, options, 'Embedded');
  43. }
  44. /*!
  45. * ignore
  46. */
  47. SubdocumentPath.prototype = Object.create(SchemaType.prototype);
  48. SubdocumentPath.prototype.constructor = SubdocumentPath;
  49. SubdocumentPath.prototype.OptionsConstructor = SchemaSubdocumentOptions;
  50. /*!
  51. * ignore
  52. */
  53. function _createConstructor(schema, baseClass) {
  54. // lazy load
  55. Subdocument || (Subdocument = require('../types/subdocument'));
  56. const _embedded = function SingleNested(value, path, parent) {
  57. this.$__parent = parent;
  58. Subdocument.apply(this, arguments);
  59. if (parent == null) {
  60. return;
  61. }
  62. this.$session(parent.$session());
  63. };
  64. schema._preCompile();
  65. const proto = baseClass != null ? baseClass.prototype : Subdocument.prototype;
  66. _embedded.prototype = Object.create(proto);
  67. _embedded.prototype.$__setSchema(schema);
  68. _embedded.prototype.constructor = _embedded;
  69. _embedded.schema = schema;
  70. _embedded.$isSingleNested = true;
  71. _embedded.events = new EventEmitter();
  72. _embedded.prototype.toBSON = function() {
  73. return this.toObject(internalToObjectOptions);
  74. };
  75. // apply methods
  76. for (const i in schema.methods) {
  77. _embedded.prototype[i] = schema.methods[i];
  78. }
  79. // apply statics
  80. for (const i in schema.statics) {
  81. _embedded[i] = schema.statics[i];
  82. }
  83. for (const i in EventEmitter.prototype) {
  84. _embedded[i] = EventEmitter.prototype[i];
  85. }
  86. return _embedded;
  87. }
  88. /*!
  89. * Special case for when users use a common location schema to represent
  90. * locations for use with $geoWithin.
  91. * https://docs.mongodb.org/manual/reference/operator/query/geoWithin/
  92. *
  93. * @param {Object} val
  94. * @api private
  95. */
  96. SubdocumentPath.prototype.$conditionalHandlers.$geoWithin = function handle$geoWithin(val) {
  97. return { $geometry: this.castForQuery(val.$geometry) };
  98. };
  99. /*!
  100. * ignore
  101. */
  102. SubdocumentPath.prototype.$conditionalHandlers.$near =
  103. SubdocumentPath.prototype.$conditionalHandlers.$nearSphere = geospatial.cast$near;
  104. SubdocumentPath.prototype.$conditionalHandlers.$within =
  105. SubdocumentPath.prototype.$conditionalHandlers.$geoWithin = geospatial.cast$within;
  106. SubdocumentPath.prototype.$conditionalHandlers.$geoIntersects =
  107. geospatial.cast$geoIntersects;
  108. SubdocumentPath.prototype.$conditionalHandlers.$minDistance = castToNumber;
  109. SubdocumentPath.prototype.$conditionalHandlers.$maxDistance = castToNumber;
  110. SubdocumentPath.prototype.$conditionalHandlers.$exists = $exists;
  111. /**
  112. * Casts contents
  113. *
  114. * @param {Object} value
  115. * @api private
  116. */
  117. SubdocumentPath.prototype.cast = function(val, doc, init, priorVal, options) {
  118. if (val && val.$isSingleNested && val.parent === doc) {
  119. return val;
  120. }
  121. if (val != null && (typeof val !== 'object' || Array.isArray(val))) {
  122. throw new ObjectExpectedError(this.path, val);
  123. }
  124. const Constructor = getConstructor(this.caster, val);
  125. let subdoc;
  126. // Only pull relevant selected paths and pull out the base path
  127. const parentSelected = doc && doc.$__ && doc.$__.selected || {};
  128. const path = this.path;
  129. const selected = Object.keys(parentSelected).reduce((obj, key) => {
  130. if (key.startsWith(path + '.')) {
  131. obj = obj || {};
  132. obj[key.substring(path.length + 1)] = parentSelected[key];
  133. }
  134. return obj;
  135. }, null);
  136. options = Object.assign({}, options, { priorDoc: priorVal });
  137. if (init) {
  138. subdoc = new Constructor(void 0, selected, doc);
  139. subdoc.$init(val);
  140. } else {
  141. if (Object.keys(val).length === 0) {
  142. return new Constructor({}, selected, doc, undefined, options);
  143. }
  144. return new Constructor(val, selected, doc, undefined, options);
  145. }
  146. return subdoc;
  147. };
  148. /**
  149. * Casts contents for query
  150. *
  151. * @param {string} [$conditional] optional query operator (like `$eq` or `$in`)
  152. * @param {any} value
  153. * @api private
  154. */
  155. SubdocumentPath.prototype.castForQuery = function($conditional, val, options) {
  156. let handler;
  157. if (arguments.length === 2) {
  158. handler = this.$conditionalHandlers[$conditional];
  159. if (!handler) {
  160. throw new Error('Can\'t use ' + $conditional);
  161. }
  162. return handler.call(this, val);
  163. }
  164. val = $conditional;
  165. if (val == null) {
  166. return val;
  167. }
  168. if (this.options.runSetters) {
  169. val = this._applySetters(val);
  170. }
  171. const Constructor = getConstructor(this.caster, val);
  172. const overrideStrict = options != null && options.strict != null ?
  173. options.strict :
  174. void 0;
  175. try {
  176. val = new Constructor(val, overrideStrict);
  177. } catch (error) {
  178. // Make sure we always wrap in a CastError (gh-6803)
  179. if (!(error instanceof CastError)) {
  180. throw new CastError('Embedded', val, this.path, error, this);
  181. }
  182. throw error;
  183. }
  184. return val;
  185. };
  186. /**
  187. * Async validation on this single nested doc.
  188. *
  189. * @api private
  190. */
  191. SubdocumentPath.prototype.doValidate = function(value, fn, scope, options) {
  192. const Constructor = getConstructor(this.caster, value);
  193. if (value && !(value instanceof Constructor)) {
  194. value = new Constructor(value, null, (scope != null && scope.$__ != null) ? scope : null);
  195. }
  196. if (options && options.skipSchemaValidators) {
  197. if (!value) {
  198. return fn(null);
  199. }
  200. return value.validate(fn);
  201. }
  202. SchemaType.prototype.doValidate.call(this, value, function(error) {
  203. if (error) {
  204. return fn(error);
  205. }
  206. if (!value) {
  207. return fn(null);
  208. }
  209. value.validate(fn);
  210. }, scope, options);
  211. };
  212. /**
  213. * Synchronously validate this single nested doc
  214. *
  215. * @api private
  216. */
  217. SubdocumentPath.prototype.doValidateSync = function(value, scope, options) {
  218. if (!options || !options.skipSchemaValidators) {
  219. const schemaTypeError = SchemaType.prototype.doValidateSync.call(this, value, scope);
  220. if (schemaTypeError) {
  221. return schemaTypeError;
  222. }
  223. }
  224. if (!value) {
  225. return;
  226. }
  227. return value.validateSync();
  228. };
  229. /**
  230. * Adds a discriminator to this single nested subdocument.
  231. *
  232. * #### Example:
  233. * const shapeSchema = Schema({ name: String }, { discriminatorKey: 'kind' });
  234. * const schema = Schema({ shape: shapeSchema });
  235. *
  236. * const singleNestedPath = parentSchema.path('shape');
  237. * singleNestedPath.discriminator('Circle', Schema({ radius: Number }));
  238. *
  239. * @param {String} name
  240. * @param {Schema} schema fields to add to the schema for instances of this sub-class
  241. * @param {Object|string} [options] If string, same as `options.value`.
  242. * @param {String} [options.value] the string stored in the `discriminatorKey` property. If not specified, Mongoose uses the `name` parameter.
  243. * @param {Boolean} [options.clone=true] By default, `discriminator()` clones the given `schema`. Set to `false` to skip cloning.
  244. * @return {Function} the constructor Mongoose will use for creating instances of this discriminator model
  245. * @see discriminators /docs/discriminators.html
  246. * @api public
  247. */
  248. SubdocumentPath.prototype.discriminator = function(name, schema, options) {
  249. options = options || {};
  250. const value = utils.isPOJO(options) ? options.value : options;
  251. const clone = typeof options.clone === 'boolean'
  252. ? options.clone
  253. : true;
  254. if (schema.instanceOfSchema && clone) {
  255. schema = schema.clone();
  256. }
  257. schema = discriminator(this.caster, name, schema, value);
  258. this.caster.discriminators[name] = _createConstructor(schema, this.caster);
  259. return this.caster.discriminators[name];
  260. };
  261. /**
  262. * Sets a default option for all SubdocumentPath instances.
  263. *
  264. * #### Example:
  265. *
  266. * // Make all numbers have option `min` equal to 0.
  267. * mongoose.Schema.Embedded.set('required', true);
  268. *
  269. * @param {String} option - The option you'd like to set the value for
  270. * @param {*} value - value for option
  271. * @return {undefined}
  272. * @function set
  273. * @static
  274. * @api public
  275. */
  276. SubdocumentPath.defaultOptions = {};
  277. SubdocumentPath.set = SchemaType.set;
  278. /*!
  279. * ignore
  280. */
  281. SubdocumentPath.prototype.clone = function() {
  282. const options = Object.assign({}, this.options);
  283. const schematype = new this.constructor(this.schema, this.path, options);
  284. schematype.validators = this.validators.slice();
  285. if (this.requiredValidator !== undefined) {
  286. schematype.requiredValidator = this.requiredValidator;
  287. }
  288. schematype.caster.discriminators = Object.assign({}, this.caster.discriminators);
  289. return schematype;
  290. };