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 get = require('../helpers/get');
  15. const getConstructor = require('../helpers/discriminator/getConstructor');
  16. const handleIdOption = require('../helpers/schema/handleIdOption');
  17. const internalToObjectOptions = require('../options').internalToObjectOptions;
  18. const utils = require('../utils');
  19. let Subdocument;
  20. module.exports = SubdocumentPath;
  21. /**
  22. * Single nested subdocument SchemaType constructor.
  23. *
  24. * @param {Schema} schema
  25. * @param {String} key
  26. * @param {Object} options
  27. * @inherits SchemaType
  28. * @api public
  29. */
  30. function SubdocumentPath(schema, path, options) {
  31. schema = handleIdOption(schema, options);
  32. this.caster = _createConstructor(schema);
  33. this.caster.path = path;
  34. this.caster.prototype.$basePath = path;
  35. this.schema = schema;
  36. this.$isSingleNested = true;
  37. SchemaType.call(this, path, options, 'Embedded');
  38. }
  39. /*!
  40. * ignore
  41. */
  42. SubdocumentPath.prototype = Object.create(SchemaType.prototype);
  43. SubdocumentPath.prototype.constructor = SubdocumentPath;
  44. SubdocumentPath.prototype.OptionsConstructor = SchemaSubdocumentOptions;
  45. /*!
  46. * ignore
  47. */
  48. function _createConstructor(schema, baseClass) {
  49. // lazy load
  50. Subdocument || (Subdocument = require('../types/subdocument'));
  51. const _embedded = function SingleNested(value, path, parent) {
  52. const _this = this;
  53. this.$__parent = parent;
  54. Subdocument.apply(this, arguments);
  55. this.$session(this.ownerDocument().$session());
  56. if (parent) {
  57. parent.$on('save', function() {
  58. _this.emit('save', _this);
  59. _this.constructor.emit('save', _this);
  60. });
  61. parent.$on('isNew', function(val) {
  62. _this.isNew = val;
  63. _this.emit('isNew', val);
  64. _this.constructor.emit('isNew', val);
  65. });
  66. }
  67. };
  68. schema._preCompile();
  69. const proto = baseClass != null ? baseClass.prototype : Subdocument.prototype;
  70. _embedded.prototype = Object.create(proto);
  71. _embedded.prototype.$__setSchema(schema);
  72. _embedded.prototype.constructor = _embedded;
  73. _embedded.schema = schema;
  74. _embedded.$isSingleNested = true;
  75. _embedded.events = new EventEmitter();
  76. _embedded.prototype.toBSON = function() {
  77. return this.toObject(internalToObjectOptions);
  78. };
  79. // apply methods
  80. for (const i in schema.methods) {
  81. _embedded.prototype[i] = schema.methods[i];
  82. }
  83. // apply statics
  84. for (const i in schema.statics) {
  85. _embedded[i] = schema.statics[i];
  86. }
  87. for (const i in EventEmitter.prototype) {
  88. _embedded[i] = EventEmitter.prototype[i];
  89. }
  90. return _embedded;
  91. }
  92. /*!
  93. * Special case for when users use a common location schema to represent
  94. * locations for use with $geoWithin.
  95. * https://docs.mongodb.org/manual/reference/operator/query/geoWithin/
  96. *
  97. * @param {Object} val
  98. * @api private
  99. */
  100. SubdocumentPath.prototype.$conditionalHandlers.$geoWithin = function handle$geoWithin(val) {
  101. return { $geometry: this.castForQuery(val.$geometry) };
  102. };
  103. /*!
  104. * ignore
  105. */
  106. SubdocumentPath.prototype.$conditionalHandlers.$near =
  107. SubdocumentPath.prototype.$conditionalHandlers.$nearSphere = geospatial.cast$near;
  108. SubdocumentPath.prototype.$conditionalHandlers.$within =
  109. SubdocumentPath.prototype.$conditionalHandlers.$geoWithin = geospatial.cast$within;
  110. SubdocumentPath.prototype.$conditionalHandlers.$geoIntersects =
  111. geospatial.cast$geoIntersects;
  112. SubdocumentPath.prototype.$conditionalHandlers.$minDistance = castToNumber;
  113. SubdocumentPath.prototype.$conditionalHandlers.$maxDistance = castToNumber;
  114. SubdocumentPath.prototype.$conditionalHandlers.$exists = $exists;
  115. /**
  116. * Casts contents
  117. *
  118. * @param {Object} value
  119. * @api private
  120. */
  121. SubdocumentPath.prototype.cast = function(val, doc, init, priorVal, options) {
  122. if (val && val.$isSingleNested && val.parent === doc) {
  123. return val;
  124. }
  125. if (val != null && (typeof val !== 'object' || Array.isArray(val))) {
  126. throw new ObjectExpectedError(this.path, val);
  127. }
  128. const Constructor = getConstructor(this.caster, val);
  129. let subdoc;
  130. // Only pull relevant selected paths and pull out the base path
  131. const parentSelected = get(doc, '$__.selected', {});
  132. const path = this.path;
  133. const selected = Object.keys(parentSelected).reduce((obj, key) => {
  134. if (key.startsWith(path + '.')) {
  135. obj[key.substring(path.length + 1)] = parentSelected[key];
  136. }
  137. return obj;
  138. }, {});
  139. options = Object.assign({}, options, { priorDoc: priorVal });
  140. if (init) {
  141. subdoc = new Constructor(void 0, selected, doc);
  142. subdoc.$init(val);
  143. } else {
  144. if (Object.keys(val).length === 0) {
  145. return new Constructor({}, selected, doc, undefined, options);
  146. }
  147. return new Constructor(val, selected, doc, undefined, options);
  148. }
  149. return subdoc;
  150. };
  151. /**
  152. * Casts contents for query
  153. *
  154. * @param {string} [$conditional] optional query operator (like `$eq` or `$in`)
  155. * @param {any} value
  156. * @api private
  157. */
  158. SubdocumentPath.prototype.castForQuery = function($conditional, val, options) {
  159. let handler;
  160. if (arguments.length === 2) {
  161. handler = this.$conditionalHandlers[$conditional];
  162. if (!handler) {
  163. throw new Error('Can\'t use ' + $conditional);
  164. }
  165. return handler.call(this, val);
  166. }
  167. val = $conditional;
  168. if (val == null) {
  169. return val;
  170. }
  171. if (this.options.runSetters) {
  172. val = this._applySetters(val);
  173. }
  174. const Constructor = getConstructor(this.caster, val);
  175. const overrideStrict = options != null && options.strict != null ?
  176. options.strict :
  177. void 0;
  178. try {
  179. val = new Constructor(val, overrideStrict);
  180. } catch (error) {
  181. // Make sure we always wrap in a CastError (gh-6803)
  182. if (!(error instanceof CastError)) {
  183. throw new CastError('Embedded', val, this.path, error, this);
  184. }
  185. throw error;
  186. }
  187. return val;
  188. };
  189. /**
  190. * Async validation on this single nested doc.
  191. *
  192. * @api private
  193. */
  194. SubdocumentPath.prototype.doValidate = function(value, fn, scope, options) {
  195. const Constructor = getConstructor(this.caster, value);
  196. if (value && !(value instanceof Constructor)) {
  197. value = new Constructor(value, null, scope);
  198. }
  199. if (options && options.skipSchemaValidators) {
  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 = get(options, 'clone', true);
  252. if (schema.instanceOfSchema && clone) {
  253. schema = schema.clone();
  254. }
  255. schema = discriminator(this.caster, name, schema, value);
  256. this.caster.discriminators[name] = _createConstructor(schema, this.caster);
  257. return this.caster.discriminators[name];
  258. };
  259. /**
  260. * Sets a default option for all SubdocumentPath instances.
  261. *
  262. * ####Example:
  263. *
  264. * // Make all numbers have option `min` equal to 0.
  265. * mongoose.Schema.Embedded.set('required', true);
  266. *
  267. * @param {String} option - The option you'd like to set the value for
  268. * @param {*} value - value for option
  269. * @return {undefined}
  270. * @function set
  271. * @static
  272. * @api public
  273. */
  274. SubdocumentPath.defaultOptions = {};
  275. SubdocumentPath.set = SchemaType.set;
  276. /*!
  277. * ignore
  278. */
  279. SubdocumentPath.prototype.clone = function() {
  280. const options = Object.assign({}, this.options);
  281. const schematype = new this.constructor(this.schema, this.path, options);
  282. schematype.validators = this.validators.slice();
  283. if (this.requiredValidator !== undefined) {
  284. schematype.requiredValidator = this.requiredValidator;
  285. }
  286. schematype.caster.discriminators = Object.assign({}, this.caster.discriminators);
  287. return schematype;
  288. };