Spaces:
Runtime error
Runtime error
File size: 11,261 Bytes
9756872 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 | '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 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
* @inherits SchemaType
* @api public
*/
function SchemaSubdocument(schema, path, options) {
if (schema.options.timeseries) {
throw new InvalidSchemaOptionError(path, 'timeseries');
}
const schemaTypeIdOption = SchemaSubdocument.defaultOptions &&
SchemaSubdocument.defaultOptions._id;
if (schemaTypeIdOption != null) {
options = options || {};
options._id = schemaTypeIdOption;
}
schema = handleIdOption(schema, options);
this.caster = _createConstructor(schema, null, options);
this.caster.path = path;
this.caster.prototype.$basePath = path;
this.schema = schema;
this.$isSingleNested = true;
this.base = schema.base;
SchemaType.call(this, path, options, 'Embedded');
}
/*!
* 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 != null ? baseClass.prototype : SubdocumentType.prototype;
_embedded.prototype = Object.create(proto);
_embedded.prototype.$__setSchema(schema);
_embedded.prototype.constructor = _embedded;
_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;
}
/**
* 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
*/
SchemaSubdocument.prototype.$conditionalHandlers.$geoWithin = function handle$geoWithin(val, context) {
return { $geometry: this.castForQuery(null, val.$geometry, context) };
};
/*!
* ignore
*/
SchemaSubdocument.prototype.$conditionalHandlers.$near =
SchemaSubdocument.prototype.$conditionalHandlers.$nearSphere = geospatial.cast$near;
SchemaSubdocument.prototype.$conditionalHandlers.$within =
SchemaSubdocument.prototype.$conditionalHandlers.$geoWithin = geospatial.cast$within;
SchemaSubdocument.prototype.$conditionalHandlers.$geoIntersects =
geospatial.cast$geoIntersects;
SchemaSubdocument.prototype.$conditionalHandlers.$minDistance = castToNumber;
SchemaSubdocument.prototype.$conditionalHandlers.$maxDistance = castToNumber;
SchemaSubdocument.prototype.$conditionalHandlers.$exists = $exists;
/**
* Casts contents
*
* @param {Object} value
* @api private
*/
SchemaSubdocument.prototype.cast = function(val, doc, init, priorVal, options) {
if (val && val.$isSingleNested && val.parent === doc) {
return val;
}
if (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.caster, val, defaultDiscriminatorValue);
let subdoc;
// Only pull relevant selected paths and pull out the base path
const parentSelected = doc && doc.$__ && 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, false, { defaults: false });
delete subdoc.$__.defaults;
subdoc.$init(val);
const exclude = isExclusive(selected);
applyDefaults(subdoc, selected, exclude);
} else {
options = Object.assign({}, options, { priorDoc: priorVal });
if (Object.keys(val).length === 0) {
return new Constructor({}, selected, doc, undefined, options);
}
return new Constructor(val, selected, doc, undefined, 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.caster, val);
if (val instanceof Constructor) {
return val;
}
if (this.options.runSetters) {
val = this._applySetters(val, context);
}
const overrideStrict = options != null && options.strict != null ?
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 private
*/
SchemaSubdocument.prototype.doValidate = function(value, fn, scope, options) {
const Constructor = getConstructor(this.caster, value);
if (value && !(value instanceof Constructor)) {
value = new Constructor(value, null, (scope != null && scope.$__ != null) ? scope : null);
}
if (options && options.skipSchemaValidators) {
if (!value) {
return fn(null);
}
return value.validate().then(() => fn(null), err => fn(err));
}
SchemaType.prototype.doValidate.call(this, value, function(error) {
if (error) {
return fn(error);
}
if (!value) {
return fn(null);
}
value.validate().then(() => fn(null), err => fn(err));
}, scope, options);
};
/**
* Synchronously validate this single nested doc
*
* @api private
*/
SchemaSubdocument.prototype.doValidateSync = function(value, scope, options) {
if (!options || !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.caster, name, schema, value, null, null, options.overwriteExisting);
this.caster.discriminators[name] = _createConstructor(schema, this.caster);
return this.caster.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 }
);
schematype.validators = this.validators.slice();
if (this.requiredValidator !== undefined) {
schematype.requiredValidator = this.requiredValidator;
}
schematype.caster.discriminators = Object.assign({}, this.caster.discriminators);
return schematype;
};
|