SingleNestedPath.js 9.0 KB

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