| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436 |
- 'use strict';
- /*!
- * Module dependencies.
- */
- const CastError = require('../error/cast');
- const EventEmitter = require('events').EventEmitter;
- const ObjectExpectedError = require('../error/objectExpected');
- const SchemaSubdocumentOptions = require('../options/schemaSubdocumentOptions');
- const SchemaType = require('../schemaType');
- const applyDefaults = require('../helpers/document/applyDefaults');
- const $exists = require('./operators/exists');
- const castToNumber = require('./operators/helpers').castToNumber;
- const createJSONSchemaTypeDefinition = require('../helpers/createJSONSchemaTypeDefinition');
- const discriminator = require('../helpers/model/discriminator');
- const geospatial = require('./operators/geospatial');
- const getConstructor = require('../helpers/discriminator/getConstructor');
- const handleIdOption = require('../helpers/schema/handleIdOption');
- const internalToObjectOptions = require('../options').internalToObjectOptions;
- const isExclusive = require('../helpers/projection/isExclusive');
- const utils = require('../utils');
- const InvalidSchemaOptionError = require('../error/invalidSchemaOption');
- let SubdocumentType;
- module.exports = SchemaSubdocument;
- /**
- * Single nested subdocument SchemaType constructor.
- *
- * @param {Schema} schema
- * @param {String} path
- * @param {Object} options
- * @param {Schema} parentSchema
- * @inherits SchemaType
- * @api public
- */
- function SchemaSubdocument(schema, path, options, parentSchema) {
- if (schema.options.timeseries) {
- throw new InvalidSchemaOptionError(path, 'timeseries');
- }
- const schemaTypeIdOption = SchemaSubdocument.defaultOptions?._id;
- if (schemaTypeIdOption != null) {
- options = options || {};
- options._id = schemaTypeIdOption;
- }
- schema = handleIdOption(schema, options);
- this.Constructor = _createConstructor(schema, null, options);
- this.Constructor.path = path;
- this.Constructor.prototype.$basePath = path;
- this.schema = schema;
- this.$isSingleNested = true;
- this.base = schema.base;
- SchemaType.call(this, path, options, 'Embedded', parentSchema);
- }
- /*!
- * ignore
- */
- SchemaSubdocument.prototype = Object.create(SchemaType.prototype);
- SchemaSubdocument.prototype.constructor = SchemaSubdocument;
- SchemaSubdocument.prototype.OptionsConstructor = SchemaSubdocumentOptions;
- /*!
- * ignore
- */
- function _createConstructor(schema, baseClass, options) {
- // lazy load
- SubdocumentType || (SubdocumentType = require('../types/subdocument'));
- const _embedded = function SingleNested(value, path, parent) {
- this.$__parent = parent;
- SubdocumentType.apply(this, arguments);
- if (parent == null) {
- return;
- }
- this.$session(parent.$session());
- };
- schema._preCompile();
- const proto = baseClass?.prototype ?? SubdocumentType.prototype;
- _embedded.prototype = Object.create(proto);
- _embedded.prototype.$__setSchema(schema);
- _embedded.prototype.constructor = _embedded;
- _embedded.prototype.$__schemaTypeOptions = options;
- _embedded.$__required = options?.required;
- _embedded.base = schema.base;
- _embedded.schema = schema;
- _embedded.$isSingleNested = true;
- _embedded.events = new EventEmitter();
- _embedded.prototype.toBSON = function() {
- return this.toObject(internalToObjectOptions);
- };
- // apply methods
- for (const i in schema.methods) {
- _embedded.prototype[i] = schema.methods[i];
- }
- // apply statics
- for (const i in schema.statics) {
- _embedded[i] = schema.statics[i];
- }
- for (const i in EventEmitter.prototype) {
- _embedded[i] = EventEmitter.prototype[i];
- }
- return _embedded;
- }
- /*!
- * ignore
- */
- const $conditionalHandlers = { ...SchemaType.prototype.$conditionalHandlers };
- /**
- * Special case for when users use a common location schema to represent
- * locations for use with $geoWithin.
- * https://www.mongodb.com/docs/manual/reference/operator/query/geoWithin/
- *
- * @param {Object} val
- * @api private
- */
- $conditionalHandlers.$geoWithin = function handle$geoWithin(val, context) {
- return { $geometry: this.castForQuery(null, val.$geometry, context) };
- };
- /*!
- * ignore
- */
- $conditionalHandlers.$near =
- $conditionalHandlers.$nearSphere = geospatial.cast$near;
- $conditionalHandlers.$within =
- $conditionalHandlers.$geoWithin = geospatial.cast$within;
- $conditionalHandlers.$geoIntersects =
- geospatial.cast$geoIntersects;
- $conditionalHandlers.$minDistance = castToNumber;
- $conditionalHandlers.$maxDistance = castToNumber;
- $conditionalHandlers.$exists = $exists;
- /**
- * Contains the handlers for different query operators for this schema type.
- * For example, `$conditionalHandlers.$exists` is the function Mongoose calls to cast `$exists` filter operators.
- *
- * @property $conditionalHandlers
- * @memberOf SchemaSubdocument
- * @instance
- * @api public
- */
- Object.defineProperty(SchemaSubdocument.prototype, '$conditionalHandlers', {
- enumerable: false,
- value: $conditionalHandlers
- });
- /**
- * Casts contents
- *
- * @param {Object} value
- * @api private
- */
- SchemaSubdocument.prototype.cast = function(val, doc, init, priorVal, options) {
- if (val?.$isSingleNested && val.parent === doc) {
- return val;
- }
- if (!init && val != null && (typeof val !== 'object' || Array.isArray(val))) {
- throw new ObjectExpectedError(this.path, val);
- }
- const discriminatorKeyPath = this.schema.path(this.schema.options.discriminatorKey);
- const defaultDiscriminatorValue = discriminatorKeyPath == null ? null : discriminatorKeyPath.getDefault(doc);
- const Constructor = getConstructor(this.Constructor, val, defaultDiscriminatorValue);
- let subdoc;
- // Only pull relevant selected paths and pull out the base path
- const parentSelected = doc?.$__?.selected;
- const path = this.path;
- const selected = parentSelected == null ? null : Object.keys(parentSelected).reduce((obj, key) => {
- if (key.startsWith(path + '.')) {
- obj = obj || {};
- obj[key.substring(path.length + 1)] = parentSelected[key];
- }
- return obj;
- }, null);
- if (init) {
- subdoc = new Constructor(void 0, selected, doc, { defaults: false });
- delete subdoc.$__.defaults;
- // Don't pass `path` to $init - it's only for the subdocument itself, not its fields.
- // For change tracking, subdocuments use relative paths internally.
- // Here, `options.path` contains the absolute path and is only used by the subdocument constructor, not by $init.
- if (options.path != null) {
- options = { ...options };
- delete options.path;
- }
- subdoc.$init(val, options);
- const exclude = isExclusive(selected);
- applyDefaults(subdoc, selected, exclude);
- } else {
- options = Object.assign({}, options, { priorDoc: priorVal });
- if (utils.hasOwnKeys(val) === false) {
- return new Constructor({}, selected, doc, options);
- }
- return new Constructor(val, selected, doc, options);
- }
- return subdoc;
- };
- /**
- * Casts contents for query
- *
- * @param {string} [$conditional] optional query operator (like `$eq` or `$in`)
- * @param {any} value
- * @api private
- */
- SchemaSubdocument.prototype.castForQuery = function($conditional, val, context, options) {
- let handler;
- if ($conditional != null) {
- handler = this.$conditionalHandlers[$conditional];
- if (!handler) {
- throw new Error('Can\'t use ' + $conditional);
- }
- return handler.call(this, val);
- }
- if (val == null) {
- return val;
- }
- const Constructor = getConstructor(this.Constructor, val);
- if (val instanceof Constructor) {
- return val;
- }
- if (this.options.runSetters) {
- val = this._applySetters(val, context);
- }
- const overrideStrict = options?.strict ?? void 0;
- try {
- val = new Constructor(val, overrideStrict);
- } catch (error) {
- // Make sure we always wrap in a CastError (gh-6803)
- if (!(error instanceof CastError)) {
- throw new CastError('Embedded', val, this.path, error, this);
- }
- throw error;
- }
- return val;
- };
- /**
- * Async validation on this single nested doc.
- *
- * @api public
- */
- SchemaSubdocument.prototype.doValidate = async function doValidate(value, scope, options) {
- const Constructor = getConstructor(this.Constructor, value);
- if (value && !(value instanceof Constructor)) {
- value = new Constructor(value, null, scope?.$__ != null ? scope : null);
- }
- if (options?.skipSchemaValidators) {
- if (!value) {
- return;
- }
- return value.validate();
- }
- await SchemaType.prototype.doValidate.call(this, value, scope, options);
- if (value != null) {
- await value.validate();
- }
- };
- /**
- * Synchronously validate this single nested doc
- *
- * @api private
- */
- SchemaSubdocument.prototype.doValidateSync = function(value, scope, options) {
- if (!options?.skipSchemaValidators) {
- const schemaTypeError = SchemaType.prototype.doValidateSync.call(this, value, scope);
- if (schemaTypeError) {
- return schemaTypeError;
- }
- }
- if (!value) {
- return;
- }
- return value.validateSync();
- };
- /**
- * Adds a discriminator to this single nested subdocument.
- *
- * #### Example:
- *
- * const shapeSchema = Schema({ name: String }, { discriminatorKey: 'kind' });
- * const schema = Schema({ shape: shapeSchema });
- *
- * const singleNestedPath = parentSchema.path('shape');
- * singleNestedPath.discriminator('Circle', Schema({ radius: Number }));
- *
- * @param {String} name
- * @param {Schema} schema fields to add to the schema for instances of this sub-class
- * @param {Object|string} [options] If string, same as `options.value`.
- * @param {String} [options.value] the string stored in the `discriminatorKey` property. If not specified, Mongoose uses the `name` parameter.
- * @param {Boolean} [options.clone=true] By default, `discriminator()` clones the given `schema`. Set to `false` to skip cloning.
- * @return {Function} the constructor Mongoose will use for creating instances of this discriminator model
- * @see discriminators https://mongoosejs.com/docs/discriminators.html
- * @api public
- */
- SchemaSubdocument.prototype.discriminator = function(name, schema, options) {
- options = options || {};
- const value = utils.isPOJO(options) ? options.value : options;
- const clone = typeof options.clone === 'boolean'
- ? options.clone
- : true;
- if (schema.instanceOfSchema && clone) {
- schema = schema.clone();
- }
- schema = discriminator(this.Constructor, name, schema, value, null, null, options.overwriteExisting);
- this.Constructor.discriminators[name] = _createConstructor(schema, this.Constructor);
- return this.Constructor.discriminators[name];
- };
- /*!
- * ignore
- */
- SchemaSubdocument.defaultOptions = {};
- /**
- * Sets a default option for all Subdocument instances.
- *
- * #### Example:
- *
- * // Make all numbers have option `min` equal to 0.
- * mongoose.Schema.Subdocument.set('required', true);
- *
- * @param {String} option The option you'd like to set the value for
- * @param {Any} value value for option
- * @return {void}
- * @function set
- * @static
- * @api public
- */
- SchemaSubdocument.set = SchemaType.set;
- SchemaSubdocument.setters = [];
- /**
- * Attaches a getter for all Subdocument instances
- *
- * @param {Function} getter
- * @return {this}
- * @function get
- * @static
- * @api public
- */
- SchemaSubdocument.get = SchemaType.get;
- /*!
- * ignore
- */
- SchemaSubdocument.prototype.toJSON = function toJSON() {
- return { path: this.path, options: this.options };
- };
- /*!
- * ignore
- */
- SchemaSubdocument.prototype.clone = function() {
- const schematype = new this.constructor(
- this.schema,
- this.path,
- { ...this.options, _skipApplyDiscriminators: true },
- this.parentSchema
- );
- schematype.validators = this.validators.slice();
- if (this.requiredValidator !== undefined) {
- schematype.requiredValidator = this.requiredValidator;
- }
- schematype.Constructor.discriminators = Object.assign({}, this.Constructor.discriminators);
- schematype._appliedDiscriminators = this._appliedDiscriminators;
- return schematype;
- };
- /**
- * Returns this schema type's representation in a JSON schema.
- *
- * @param [options]
- * @param [options.useBsonType=false] If true, return a representation with `bsonType` for use with MongoDB's `$jsonSchema`.
- * @returns {Object} JSON schema properties
- */
- SchemaSubdocument.prototype.toJSONSchema = function toJSONSchema(options) {
- const isRequired = this.options.required && typeof this.options.required !== 'function';
- return {
- ...this.schema.toJSONSchema(options),
- ...createJSONSchemaTypeDefinition('object', 'object', options?.useBsonType, isRequired)
- };
- };
|