subdocument.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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 applyDefaults = require('../helpers/document/applyDefaults');
  11. const $exists = require('./operators/exists');
  12. const castToNumber = require('./operators/helpers').castToNumber;
  13. const createJSONSchemaTypeDefinition = require('../helpers/createJSONSchemaTypeDefinition');
  14. const discriminator = require('../helpers/model/discriminator');
  15. const geospatial = require('./operators/geospatial');
  16. const getConstructor = require('../helpers/discriminator/getConstructor');
  17. const handleIdOption = require('../helpers/schema/handleIdOption');
  18. const internalToObjectOptions = require('../options').internalToObjectOptions;
  19. const isExclusive = require('../helpers/projection/isExclusive');
  20. const utils = require('../utils');
  21. const InvalidSchemaOptionError = require('../error/invalidSchemaOption');
  22. let SubdocumentType;
  23. module.exports = SchemaSubdocument;
  24. /**
  25. * Single nested subdocument SchemaType constructor.
  26. *
  27. * @param {Schema} schema
  28. * @param {String} path
  29. * @param {Object} options
  30. * @param {Schema} parentSchema
  31. * @inherits SchemaType
  32. * @api public
  33. */
  34. function SchemaSubdocument(schema, path, options, parentSchema) {
  35. if (schema.options.timeseries) {
  36. throw new InvalidSchemaOptionError(path, 'timeseries');
  37. }
  38. const schemaTypeIdOption = SchemaSubdocument.defaultOptions?._id;
  39. if (schemaTypeIdOption != null) {
  40. options = options || {};
  41. options._id = schemaTypeIdOption;
  42. }
  43. schema = handleIdOption(schema, options);
  44. this.Constructor = _createConstructor(schema, null, options);
  45. this.Constructor.path = path;
  46. this.Constructor.prototype.$basePath = path;
  47. this.schema = schema;
  48. this.$isSingleNested = true;
  49. this.base = schema.base;
  50. SchemaType.call(this, path, options, 'Embedded', parentSchema);
  51. }
  52. /*!
  53. * ignore
  54. */
  55. SchemaSubdocument.prototype = Object.create(SchemaType.prototype);
  56. SchemaSubdocument.prototype.constructor = SchemaSubdocument;
  57. SchemaSubdocument.prototype.OptionsConstructor = SchemaSubdocumentOptions;
  58. /*!
  59. * ignore
  60. */
  61. function _createConstructor(schema, baseClass, options) {
  62. // lazy load
  63. SubdocumentType || (SubdocumentType = require('../types/subdocument'));
  64. const _embedded = function SingleNested(value, path, parent) {
  65. this.$__parent = parent;
  66. SubdocumentType.apply(this, arguments);
  67. if (parent == null) {
  68. return;
  69. }
  70. this.$session(parent.$session());
  71. };
  72. schema._preCompile();
  73. const proto = baseClass?.prototype ?? SubdocumentType.prototype;
  74. _embedded.prototype = Object.create(proto);
  75. _embedded.prototype.$__setSchema(schema);
  76. _embedded.prototype.constructor = _embedded;
  77. _embedded.prototype.$__schemaTypeOptions = options;
  78. _embedded.$__required = options?.required;
  79. _embedded.base = schema.base;
  80. _embedded.schema = schema;
  81. _embedded.$isSingleNested = true;
  82. _embedded.events = new EventEmitter();
  83. _embedded.prototype.toBSON = function() {
  84. return this.toObject(internalToObjectOptions);
  85. };
  86. // apply methods
  87. for (const i in schema.methods) {
  88. _embedded.prototype[i] = schema.methods[i];
  89. }
  90. // apply statics
  91. for (const i in schema.statics) {
  92. _embedded[i] = schema.statics[i];
  93. }
  94. for (const i in EventEmitter.prototype) {
  95. _embedded[i] = EventEmitter.prototype[i];
  96. }
  97. return _embedded;
  98. }
  99. /*!
  100. * ignore
  101. */
  102. const $conditionalHandlers = { ...SchemaType.prototype.$conditionalHandlers };
  103. /**
  104. * Special case for when users use a common location schema to represent
  105. * locations for use with $geoWithin.
  106. * https://www.mongodb.com/docs/manual/reference/operator/query/geoWithin/
  107. *
  108. * @param {Object} val
  109. * @api private
  110. */
  111. $conditionalHandlers.$geoWithin = function handle$geoWithin(val, context) {
  112. return { $geometry: this.castForQuery(null, val.$geometry, context) };
  113. };
  114. /*!
  115. * ignore
  116. */
  117. $conditionalHandlers.$near =
  118. $conditionalHandlers.$nearSphere = geospatial.cast$near;
  119. $conditionalHandlers.$within =
  120. $conditionalHandlers.$geoWithin = geospatial.cast$within;
  121. $conditionalHandlers.$geoIntersects =
  122. geospatial.cast$geoIntersects;
  123. $conditionalHandlers.$minDistance = castToNumber;
  124. $conditionalHandlers.$maxDistance = castToNumber;
  125. $conditionalHandlers.$exists = $exists;
  126. /**
  127. * Contains the handlers for different query operators for this schema type.
  128. * For example, `$conditionalHandlers.$exists` is the function Mongoose calls to cast `$exists` filter operators.
  129. *
  130. * @property $conditionalHandlers
  131. * @memberOf SchemaSubdocument
  132. * @instance
  133. * @api public
  134. */
  135. Object.defineProperty(SchemaSubdocument.prototype, '$conditionalHandlers', {
  136. enumerable: false,
  137. value: $conditionalHandlers
  138. });
  139. /**
  140. * Casts contents
  141. *
  142. * @param {Object} value
  143. * @api private
  144. */
  145. SchemaSubdocument.prototype.cast = function(val, doc, init, priorVal, options) {
  146. if (val?.$isSingleNested && val.parent === doc) {
  147. return val;
  148. }
  149. if (!init && val != null && (typeof val !== 'object' || Array.isArray(val))) {
  150. throw new ObjectExpectedError(this.path, val);
  151. }
  152. const discriminatorKeyPath = this.schema.path(this.schema.options.discriminatorKey);
  153. const defaultDiscriminatorValue = discriminatorKeyPath == null ? null : discriminatorKeyPath.getDefault(doc);
  154. const Constructor = getConstructor(this.Constructor, val, defaultDiscriminatorValue);
  155. let subdoc;
  156. // Only pull relevant selected paths and pull out the base path
  157. const parentSelected = doc?.$__?.selected;
  158. const path = this.path;
  159. const selected = parentSelected == null ? null : Object.keys(parentSelected).reduce((obj, key) => {
  160. if (key.startsWith(path + '.')) {
  161. obj = obj || {};
  162. obj[key.substring(path.length + 1)] = parentSelected[key];
  163. }
  164. return obj;
  165. }, null);
  166. if (init) {
  167. subdoc = new Constructor(void 0, selected, doc, { defaults: false });
  168. delete subdoc.$__.defaults;
  169. // Don't pass `path` to $init - it's only for the subdocument itself, not its fields.
  170. // For change tracking, subdocuments use relative paths internally.
  171. // Here, `options.path` contains the absolute path and is only used by the subdocument constructor, not by $init.
  172. if (options.path != null) {
  173. options = { ...options };
  174. delete options.path;
  175. }
  176. subdoc.$init(val, options);
  177. const exclude = isExclusive(selected);
  178. applyDefaults(subdoc, selected, exclude);
  179. } else {
  180. options = Object.assign({}, options, { priorDoc: priorVal });
  181. if (utils.hasOwnKeys(val) === false) {
  182. return new Constructor({}, selected, doc, options);
  183. }
  184. return new Constructor(val, selected, doc, options);
  185. }
  186. return subdoc;
  187. };
  188. /**
  189. * Casts contents for query
  190. *
  191. * @param {string} [$conditional] optional query operator (like `$eq` or `$in`)
  192. * @param {any} value
  193. * @api private
  194. */
  195. SchemaSubdocument.prototype.castForQuery = function($conditional, val, context, options) {
  196. let handler;
  197. if ($conditional != null) {
  198. handler = this.$conditionalHandlers[$conditional];
  199. if (!handler) {
  200. throw new Error('Can\'t use ' + $conditional);
  201. }
  202. return handler.call(this, val);
  203. }
  204. if (val == null) {
  205. return val;
  206. }
  207. const Constructor = getConstructor(this.Constructor, val);
  208. if (val instanceof Constructor) {
  209. return val;
  210. }
  211. if (this.options.runSetters) {
  212. val = this._applySetters(val, context);
  213. }
  214. const overrideStrict = options?.strict ?? void 0;
  215. try {
  216. val = new Constructor(val, overrideStrict);
  217. } catch (error) {
  218. // Make sure we always wrap in a CastError (gh-6803)
  219. if (!(error instanceof CastError)) {
  220. throw new CastError('Embedded', val, this.path, error, this);
  221. }
  222. throw error;
  223. }
  224. return val;
  225. };
  226. /**
  227. * Async validation on this single nested doc.
  228. *
  229. * @api public
  230. */
  231. SchemaSubdocument.prototype.doValidate = async function doValidate(value, scope, options) {
  232. const Constructor = getConstructor(this.Constructor, value);
  233. if (value && !(value instanceof Constructor)) {
  234. value = new Constructor(value, null, scope?.$__ != null ? scope : null);
  235. }
  236. if (options?.skipSchemaValidators) {
  237. if (!value) {
  238. return;
  239. }
  240. return value.validate();
  241. }
  242. await SchemaType.prototype.doValidate.call(this, value, scope, options);
  243. if (value != null) {
  244. await value.validate();
  245. }
  246. };
  247. /**
  248. * Synchronously validate this single nested doc
  249. *
  250. * @api private
  251. */
  252. SchemaSubdocument.prototype.doValidateSync = function(value, scope, options) {
  253. if (!options?.skipSchemaValidators) {
  254. const schemaTypeError = SchemaType.prototype.doValidateSync.call(this, value, scope);
  255. if (schemaTypeError) {
  256. return schemaTypeError;
  257. }
  258. }
  259. if (!value) {
  260. return;
  261. }
  262. return value.validateSync();
  263. };
  264. /**
  265. * Adds a discriminator to this single nested subdocument.
  266. *
  267. * #### Example:
  268. *
  269. * const shapeSchema = Schema({ name: String }, { discriminatorKey: 'kind' });
  270. * const schema = Schema({ shape: shapeSchema });
  271. *
  272. * const singleNestedPath = parentSchema.path('shape');
  273. * singleNestedPath.discriminator('Circle', Schema({ radius: Number }));
  274. *
  275. * @param {String} name
  276. * @param {Schema} schema fields to add to the schema for instances of this sub-class
  277. * @param {Object|string} [options] If string, same as `options.value`.
  278. * @param {String} [options.value] the string stored in the `discriminatorKey` property. If not specified, Mongoose uses the `name` parameter.
  279. * @param {Boolean} [options.clone=true] By default, `discriminator()` clones the given `schema`. Set to `false` to skip cloning.
  280. * @return {Function} the constructor Mongoose will use for creating instances of this discriminator model
  281. * @see discriminators https://mongoosejs.com/docs/discriminators.html
  282. * @api public
  283. */
  284. SchemaSubdocument.prototype.discriminator = function(name, schema, options) {
  285. options = options || {};
  286. const value = utils.isPOJO(options) ? options.value : options;
  287. const clone = typeof options.clone === 'boolean'
  288. ? options.clone
  289. : true;
  290. if (schema.instanceOfSchema && clone) {
  291. schema = schema.clone();
  292. }
  293. schema = discriminator(this.Constructor, name, schema, value, null, null, options.overwriteExisting);
  294. this.Constructor.discriminators[name] = _createConstructor(schema, this.Constructor);
  295. return this.Constructor.discriminators[name];
  296. };
  297. /*!
  298. * ignore
  299. */
  300. SchemaSubdocument.defaultOptions = {};
  301. /**
  302. * Sets a default option for all Subdocument instances.
  303. *
  304. * #### Example:
  305. *
  306. * // Make all numbers have option `min` equal to 0.
  307. * mongoose.Schema.Subdocument.set('required', true);
  308. *
  309. * @param {String} option The option you'd like to set the value for
  310. * @param {Any} value value for option
  311. * @return {void}
  312. * @function set
  313. * @static
  314. * @api public
  315. */
  316. SchemaSubdocument.set = SchemaType.set;
  317. SchemaSubdocument.setters = [];
  318. /**
  319. * Attaches a getter for all Subdocument instances
  320. *
  321. * @param {Function} getter
  322. * @return {this}
  323. * @function get
  324. * @static
  325. * @api public
  326. */
  327. SchemaSubdocument.get = SchemaType.get;
  328. /*!
  329. * ignore
  330. */
  331. SchemaSubdocument.prototype.toJSON = function toJSON() {
  332. return { path: this.path, options: this.options };
  333. };
  334. /*!
  335. * ignore
  336. */
  337. SchemaSubdocument.prototype.clone = function() {
  338. const schematype = new this.constructor(
  339. this.schema,
  340. this.path,
  341. { ...this.options, _skipApplyDiscriminators: true },
  342. this.parentSchema
  343. );
  344. schematype.validators = this.validators.slice();
  345. if (this.requiredValidator !== undefined) {
  346. schematype.requiredValidator = this.requiredValidator;
  347. }
  348. schematype.Constructor.discriminators = Object.assign({}, this.Constructor.discriminators);
  349. schematype._appliedDiscriminators = this._appliedDiscriminators;
  350. return schematype;
  351. };
  352. /**
  353. * Returns this schema type's representation in a JSON schema.
  354. *
  355. * @param [options]
  356. * @param [options.useBsonType=false] If true, return a representation with `bsonType` for use with MongoDB's `$jsonSchema`.
  357. * @returns {Object} JSON schema properties
  358. */
  359. SchemaSubdocument.prototype.toJSONSchema = function toJSONSchema(options) {
  360. const isRequired = this.options.required && typeof this.options.required !== 'function';
  361. return {
  362. ...this.schema.toJSONSchema(options),
  363. ...createJSONSchemaTypeDefinition('object', 'object', options?.useBsonType, isRequired)
  364. };
  365. };