SingleNestedPath.js 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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) {
  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. 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);
  143. }
  144. return new Constructor(val, selected, doc, undefined, { priorDoc: priorVal });
  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. SingleNestedPath.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. SingleNestedPath.prototype.doValidate = function(value, fn, scope, options) {
  192. const Constructor = getConstructor(this.caster, value);
  193. if (options && options.skipSchemaValidators) {
  194. if (!(value instanceof Constructor)) {
  195. value = new Constructor(value, null, scope);
  196. }
  197. return value.validate(fn);
  198. }
  199. SchemaType.prototype.doValidate.call(this, value, function(error) {
  200. if (error) {
  201. return fn(error);
  202. }
  203. if (!value) {
  204. return fn(null);
  205. }
  206. value.validate(fn);
  207. }, scope, options);
  208. };
  209. /**
  210. * Synchronously validate this single nested doc
  211. *
  212. * @api private
  213. */
  214. SingleNestedPath.prototype.doValidateSync = function(value, scope, options) {
  215. if (!options || !options.skipSchemaValidators) {
  216. const schemaTypeError = SchemaType.prototype.doValidateSync.call(this, value, scope);
  217. if (schemaTypeError) {
  218. return schemaTypeError;
  219. }
  220. }
  221. if (!value) {
  222. return;
  223. }
  224. return value.validateSync();
  225. };
  226. /**
  227. * Adds a discriminator to this single nested subdocument.
  228. *
  229. * ####Example:
  230. * const shapeSchema = Schema({ name: String }, { discriminatorKey: 'kind' });
  231. * const schema = Schema({ shape: shapeSchema });
  232. *
  233. * const singleNestedPath = parentSchema.path('shape');
  234. * singleNestedPath.discriminator('Circle', Schema({ radius: Number }));
  235. *
  236. * @param {String} name
  237. * @param {Schema} schema fields to add to the schema for instances of this sub-class
  238. * @param {String} [value] the string stored in the `discriminatorKey` property. If not specified, Mongoose uses the `name` parameter.
  239. * @return {Function} the constructor Mongoose will use for creating instances of this discriminator model
  240. * @see discriminators /docs/discriminators.html
  241. * @api public
  242. */
  243. SingleNestedPath.prototype.discriminator = function(name, schema, value) {
  244. schema = discriminator(this.caster, name, schema, value);
  245. this.caster.discriminators[name] = _createConstructor(schema, this.caster);
  246. return this.caster.discriminators[name];
  247. };
  248. /*!
  249. * ignore
  250. */
  251. SingleNestedPath.prototype.clone = function() {
  252. const options = Object.assign({}, this.options);
  253. const schematype = new this.constructor(this.schema, this.path, options);
  254. schematype.validators = this.validators.slice();
  255. schematype.caster.discriminators = Object.assign({}, this.caster.discriminators);
  256. return schematype;
  257. };