UNPKG

91.4 kBJavaScriptView Raw
1'use strict';
2
3/*!
4 * Module dependencies.
5 */
6
7const EventEmitter = require('events').EventEmitter;
8const Kareem = require('kareem');
9const MongooseError = require('./error/mongooseError');
10const SchemaType = require('./schemaType');
11const SchemaTypeOptions = require('./options/schemaTypeOptions');
12const VirtualOptions = require('./options/virtualOptions');
13const VirtualType = require('./virtualType');
14const addAutoId = require('./helpers/schema/addAutoId');
15const clone = require('./helpers/clone');
16const get = require('./helpers/get');
17const getConstructorName = require('./helpers/getConstructorName');
18const getIndexes = require('./helpers/schema/getIndexes');
19const handleReadPreferenceAliases = require('./helpers/query/handleReadPreferenceAliases');
20const idGetter = require('./helpers/schema/idGetter');
21const merge = require('./helpers/schema/merge');
22const mpath = require('mpath');
23const setPopulatedVirtualValue = require('./helpers/populate/setPopulatedVirtualValue');
24const setupTimestamps = require('./helpers/timestamps/setupTimestamps');
25const utils = require('./utils');
26const validateRef = require('./helpers/populate/validateRef');
27const util = require('util');
28
29const hasNumericSubpathRegex = /\.\d+(\.|$)/;
30
31let MongooseTypes;
32
33const queryHooks = require('./constants').queryMiddlewareFunctions;
34const documentHooks = require('./helpers/model/applyHooks').middlewareFunctions;
35const hookNames = queryHooks.concat(documentHooks).
36 reduce((s, hook) => s.add(hook), new Set());
37
38const isPOJO = utils.isPOJO;
39
40let id = 0;
41
42const numberRE = /^\d+$/;
43
44/**
45 * Schema constructor.
46 *
47 * #### Example:
48 *
49 * const child = new Schema({ name: String });
50 * const schema = new Schema({ name: String, age: Number, children: [child] });
51 * const Tree = mongoose.model('Tree', schema);
52 *
53 * // setting schema options
54 * new Schema({ name: String }, { id: false, autoIndex: false })
55 *
56 * #### Options:
57 *
58 * - [autoIndex](https://mongoosejs.com/docs/guide.html#autoIndex): bool - defaults to null (which means use the connection's autoIndex option)
59 * - [autoCreate](https://mongoosejs.com/docs/guide.html#autoCreate): bool - defaults to null (which means use the connection's autoCreate option)
60 * - [bufferCommands](https://mongoosejs.com/docs/guide.html#bufferCommands): bool - defaults to true
61 * - [bufferTimeoutMS](https://mongoosejs.com/docs/guide.html#bufferTimeoutMS): number - defaults to 10000 (10 seconds). If `bufferCommands` is enabled, the amount of time Mongoose will wait for connectivity to be restablished before erroring out.
62 * - [capped](https://mongoosejs.com/docs/guide.html#capped): bool | number | object - defaults to false
63 * - [collection](https://mongoosejs.com/docs/guide.html#collection): string - no default
64 * - [discriminatorKey](https://mongoosejs.com/docs/guide.html#discriminatorKey): string - defaults to `__t`
65 * - [id](https://mongoosejs.com/docs/guide.html#id): bool - defaults to true
66 * - [_id](https://mongoosejs.com/docs/guide.html#_id): bool - defaults to true
67 * - [minimize](https://mongoosejs.com/docs/guide.html#minimize): bool - controls [document#toObject](https://mongoosejs.com/docs/api/document.html#Document.prototype.toObject()) behavior when called manually - defaults to true
68 * - [read](https://mongoosejs.com/docs/guide.html#read): string
69 * - [readConcern](https://mongoosejs.com/docs/guide.html#readConcern): object - defaults to null, use to set a default [read concern](https://www.mongodb.com/docs/manual/reference/read-concern/) for all queries.
70 * - [writeConcern](https://mongoosejs.com/docs/guide.html#writeConcern): object - defaults to null, use to override [the MongoDB server's default write concern settings](https://www.mongodb.com/docs/manual/reference/write-concern/)
71 * - [shardKey](https://mongoosejs.com/docs/guide.html#shardKey): object - defaults to `null`
72 * - [strict](https://mongoosejs.com/docs/guide.html#strict): bool - defaults to true
73 * - [strictQuery](https://mongoosejs.com/docs/guide.html#strictQuery): bool - defaults to false
74 * - [toJSON](https://mongoosejs.com/docs/guide.html#toJSON) - object - no default
75 * - [toObject](https://mongoosejs.com/docs/guide.html#toObject) - object - no default
76 * - [typeKey](https://mongoosejs.com/docs/guide.html#typeKey) - string - defaults to 'type'
77 * - [validateBeforeSave](https://mongoosejs.com/docs/guide.html#validateBeforeSave) - bool - defaults to `true`
78 * - [validateModifiedOnly](https://mongoosejs.com/docs/api/document.html#Document.prototype.validate()) - bool - defaults to `false`
79 * - [versionKey](https://mongoosejs.com/docs/guide.html#versionKey): string or object - defaults to "__v"
80 * - [optimisticConcurrency](https://mongoosejs.com/docs/guide.html#optimisticConcurrency): bool - defaults to false. Set to true to enable [optimistic concurrency](https://thecodebarbarian.com/whats-new-in-mongoose-5-10-optimistic-concurrency.html).
81 * - [collation](https://mongoosejs.com/docs/guide.html#collation): object - defaults to null (which means use no collation)
82 * - [timeseries](https://mongoosejs.com/docs/guide.html#timeseries): object - defaults to null (which means this schema's collection won't be a timeseries collection)
83 * - [selectPopulatedPaths](https://mongoosejs.com/docs/guide.html#selectPopulatedPaths): boolean - defaults to `true`
84 * - [skipVersioning](https://mongoosejs.com/docs/guide.html#skipVersioning): object - paths to exclude from versioning
85 * - [timestamps](https://mongoosejs.com/docs/guide.html#timestamps): object or boolean - defaults to `false`. If true, Mongoose adds `createdAt` and `updatedAt` properties to your schema and manages those properties for you.
86 * - [pluginTags](https://mongoosejs.com/docs/guide.html#pluginTags): array of strings - defaults to `undefined`. If set and plugin called with `tags` option, will only apply that plugin to schemas with a matching tag.
87 * - [virtuals](https://mongoosejs.com/docs/tutorials/virtuals.html#virtuals-via-schema-options): object - virtuals to define, alias for [`.virtual`](https://mongoosejs.com/docs/api/schema.html#Schema.prototype.virtual())
88 * - [collectionOptions]: object with options passed to [`createCollection()`](https://www.mongodb.com/docs/manual/reference/method/db.createCollection/) when calling `Model.createCollection()` or `autoCreate` set to true.
89 *
90 * #### Options for Nested Schemas:
91 *
92 * - `excludeIndexes`: bool - defaults to `false`. If `true`, skip building indexes on this schema's paths.
93 *
94 * #### Note:
95 *
96 * _When nesting schemas, (`children` in the example above), always declare the child schema first before passing it into its parent._
97 *
98 * @param {Object|Schema|Array} [definition] Can be one of: object describing schema paths, or schema to copy, or array of objects and schemas
99 * @param {Object} [options]
100 * @inherits NodeJS EventEmitter https://nodejs.org/api/events.html#class-eventemitter
101 * @event `init`: Emitted after the schema is compiled into a `Model`.
102 * @api public
103 */
104
105function Schema(obj, options) {
106 if (!(this instanceof Schema)) {
107 return new Schema(obj, options);
108 }
109
110 this.obj = obj;
111 this.paths = {};
112 this.aliases = {};
113 this.subpaths = {};
114 this.virtuals = {};
115 this.singleNestedPaths = {};
116 this.nested = {};
117 this.inherits = {};
118 this.callQueue = [];
119 this._indexes = [];
120 this._searchIndexes = [];
121 this.methods = (options && options.methods) || {};
122 this.methodOptions = {};
123 this.statics = (options && options.statics) || {};
124 this.tree = {};
125 this.query = (options && options.query) || {};
126 this.childSchemas = [];
127 this.plugins = [];
128 // For internal debugging. Do not use this to try to save a schema in MDB.
129 this.$id = ++id;
130 this.mapPaths = [];
131
132 this.s = {
133 hooks: new Kareem()
134 };
135 this.options = this.defaultOptions(options);
136
137 // build paths
138 if (Array.isArray(obj)) {
139 for (const definition of obj) {
140 this.add(definition);
141 }
142 } else if (obj) {
143 this.add(obj);
144 }
145
146 // build virtual paths
147 if (options && options.virtuals) {
148 const virtuals = options.virtuals;
149 const pathNames = Object.keys(virtuals);
150 for (const pathName of pathNames) {
151 const pathOptions = virtuals[pathName].options ? virtuals[pathName].options : undefined;
152 const virtual = this.virtual(pathName, pathOptions);
153
154 if (virtuals[pathName].get) {
155 virtual.get(virtuals[pathName].get);
156 }
157
158 if (virtuals[pathName].set) {
159 virtual.set(virtuals[pathName].set);
160 }
161 }
162 }
163
164 // check if _id's value is a subdocument (gh-2276)
165 const _idSubDoc = obj && obj._id && utils.isObject(obj._id);
166
167 // ensure the documents get an auto _id unless disabled
168 const auto_id = !this.paths['_id'] &&
169 (this.options._id) && !_idSubDoc;
170
171 if (auto_id) {
172 addAutoId(this);
173 }
174
175 this.setupTimestamp(this.options.timestamps);
176}
177
178/**
179 * Create virtual properties with alias field
180 * @api private
181 */
182function aliasFields(schema, paths) {
183 for (const path of Object.keys(paths)) {
184 let alias = null;
185 if (paths[path] != null) {
186 alias = paths[path];
187 } else {
188 const options = get(schema.paths[path], 'options');
189 if (options == null) {
190 continue;
191 }
192
193 alias = options.alias;
194 }
195
196 if (!alias) {
197 continue;
198 }
199
200 const prop = schema.paths[path].path;
201 if (Array.isArray(alias)) {
202 for (const a of alias) {
203 if (typeof a !== 'string') {
204 throw new Error('Invalid value for alias option on ' + prop + ', got ' + a);
205 }
206
207 schema.aliases[a] = prop;
208
209 schema.
210 virtual(a).
211 get((function(p) {
212 return function() {
213 if (typeof this.get === 'function') {
214 return this.get(p);
215 }
216 return this[p];
217 };
218 })(prop)).
219 set((function(p) {
220 return function(v) {
221 return this.$set(p, v);
222 };
223 })(prop));
224 }
225
226 continue;
227 }
228
229 if (typeof alias !== 'string') {
230 throw new Error('Invalid value for alias option on ' + prop + ', got ' + alias);
231 }
232
233 schema.aliases[alias] = prop;
234
235 schema.
236 virtual(alias).
237 get((function(p) {
238 return function() {
239 if (typeof this.get === 'function') {
240 return this.get(p);
241 }
242 return this[p];
243 };
244 })(prop)).
245 set((function(p) {
246 return function(v) {
247 return this.$set(p, v);
248 };
249 })(prop));
250 }
251}
252
253/*!
254 * Inherit from EventEmitter.
255 */
256Schema.prototype = Object.create(EventEmitter.prototype);
257Schema.prototype.constructor = Schema;
258Schema.prototype.instanceOfSchema = true;
259
260/*!
261 * ignore
262 */
263
264Object.defineProperty(Schema.prototype, '$schemaType', {
265 configurable: false,
266 enumerable: false,
267 writable: true
268});
269
270/**
271 * Array of child schemas (from document arrays and single nested subdocs)
272 * and their corresponding compiled models. Each element of the array is
273 * an object with 2 properties: `schema` and `model`.
274 *
275 * This property is typically only useful for plugin authors and advanced users.
276 * You do not need to interact with this property at all to use mongoose.
277 *
278 * @api public
279 * @property childSchemas
280 * @memberOf Schema
281 * @instance
282 */
283
284Object.defineProperty(Schema.prototype, 'childSchemas', {
285 configurable: false,
286 enumerable: true,
287 writable: true
288});
289
290/**
291 * Object containing all virtuals defined on this schema.
292 * The objects' keys are the virtual paths and values are instances of `VirtualType`.
293 *
294 * This property is typically only useful for plugin authors and advanced users.
295 * You do not need to interact with this property at all to use mongoose.
296 *
297 * #### Example:
298 *
299 * const schema = new Schema({});
300 * schema.virtual('answer').get(() => 42);
301 *
302 * console.log(schema.virtuals); // { answer: VirtualType { path: 'answer', ... } }
303 * console.log(schema.virtuals['answer'].getters[0].call()); // 42
304 *
305 * @api public
306 * @property virtuals
307 * @memberOf Schema
308 * @instance
309 */
310
311Object.defineProperty(Schema.prototype, 'virtuals', {
312 configurable: false,
313 enumerable: true,
314 writable: true
315});
316
317/**
318 * The original object passed to the schema constructor
319 *
320 * #### Example:
321 *
322 * const schema = new Schema({ a: String }).add({ b: String });
323 * schema.obj; // { a: String }
324 *
325 * @api public
326 * @property obj
327 * @memberOf Schema
328 * @instance
329 */
330
331Schema.prototype.obj;
332
333/**
334 * The paths defined on this schema. The keys are the top-level paths
335 * in this schema, and the values are instances of the SchemaType class.
336 *
337 * #### Example:
338 *
339 * const schema = new Schema({ name: String }, { _id: false });
340 * schema.paths; // { name: SchemaString { ... } }
341 *
342 * schema.add({ age: Number });
343 * schema.paths; // { name: SchemaString { ... }, age: SchemaNumber { ... } }
344 *
345 * @api public
346 * @property paths
347 * @memberOf Schema
348 * @instance
349 */
350
351Schema.prototype.paths;
352
353/**
354 * Schema as a tree
355 *
356 * #### Example:
357 *
358 * {
359 * '_id' : ObjectId
360 * , 'nested' : {
361 * 'key' : String
362 * }
363 * }
364 *
365 * @api private
366 * @property tree
367 * @memberOf Schema
368 * @instance
369 */
370
371Schema.prototype.tree;
372
373/**
374 * Returns a deep copy of the schema
375 *
376 * #### Example:
377 *
378 * const schema = new Schema({ name: String });
379 * const clone = schema.clone();
380 * clone === schema; // false
381 * clone.path('name'); // SchemaString { ... }
382 *
383 * @return {Schema} the cloned schema
384 * @api public
385 * @memberOf Schema
386 * @instance
387 */
388
389Schema.prototype.clone = function() {
390 const s = this._clone();
391
392 // Bubble up `init` for backwards compat
393 s.on('init', v => this.emit('init', v));
394
395 return s;
396};
397
398/*!
399 * ignore
400 */
401
402Schema.prototype._clone = function _clone(Constructor) {
403 Constructor = Constructor || (this.base == null ? Schema : this.base.Schema);
404
405 const s = new Constructor({}, this._userProvidedOptions);
406 s.base = this.base;
407 s.obj = this.obj;
408 s.options = clone(this.options);
409 s.callQueue = this.callQueue.map(function(f) { return f; });
410 s.methods = clone(this.methods);
411 s.methodOptions = clone(this.methodOptions);
412 s.statics = clone(this.statics);
413 s.query = clone(this.query);
414 s.plugins = Array.prototype.slice.call(this.plugins);
415 s._indexes = clone(this._indexes);
416 s._searchIndexes = clone(this._searchIndexes);
417 s.s.hooks = this.s.hooks.clone();
418
419 s.tree = clone(this.tree);
420 s.paths = Object.fromEntries(
421 Object.entries(this.paths).map(([key, value]) => ([key, value.clone()]))
422 );
423 s.nested = clone(this.nested);
424 s.subpaths = clone(this.subpaths);
425 for (const schemaType of Object.values(s.paths)) {
426 if (schemaType.$isSingleNested) {
427 const path = schemaType.path;
428 for (const key of Object.keys(schemaType.schema.paths)) {
429 s.singleNestedPaths[path + '.' + key] = schemaType.schema.paths[key];
430 }
431 for (const key of Object.keys(schemaType.schema.singleNestedPaths)) {
432 s.singleNestedPaths[path + '.' + key] =
433 schemaType.schema.singleNestedPaths[key];
434 }
435 for (const key of Object.keys(schemaType.schema.subpaths)) {
436 s.singleNestedPaths[path + '.' + key] =
437 schemaType.schema.subpaths[key];
438 }
439 for (const key of Object.keys(schemaType.schema.nested)) {
440 s.singleNestedPaths[path + '.' + key] = 'nested';
441 }
442 }
443 }
444 s.childSchemas = gatherChildSchemas(s);
445
446 s.virtuals = clone(this.virtuals);
447 s.$globalPluginsApplied = this.$globalPluginsApplied;
448 s.$isRootDiscriminator = this.$isRootDiscriminator;
449 s.$implicitlyCreated = this.$implicitlyCreated;
450 s.$id = ++id;
451 s.$originalSchemaId = this.$id;
452 s.mapPaths = [].concat(this.mapPaths);
453
454 if (this.discriminatorMapping != null) {
455 s.discriminatorMapping = Object.assign({}, this.discriminatorMapping);
456 }
457 if (this.discriminators != null) {
458 s.discriminators = Object.assign({}, this.discriminators);
459 }
460 if (this._applyDiscriminators != null) {
461 s._applyDiscriminators = new Map(this._applyDiscriminators);
462 }
463
464 s.aliases = Object.assign({}, this.aliases);
465
466 return s;
467};
468
469/**
470 * Returns a new schema that has the picked `paths` from this schema.
471 *
472 * This method is analagous to [Lodash's `pick()` function](https://lodash.com/docs/4.17.15#pick) for Mongoose schemas.
473 *
474 * #### Example:
475 *
476 * const schema = Schema({ name: String, age: Number });
477 * // Creates a new schema with the same `name` path as `schema`,
478 * // but no `age` path.
479 * const newSchema = schema.pick(['name']);
480 *
481 * newSchema.path('name'); // SchemaString { ... }
482 * newSchema.path('age'); // undefined
483 *
484 * @param {String[]} paths List of Paths to pick for the new Schema
485 * @param {Object} [options] Options to pass to the new Schema Constructor (same as `new Schema(.., Options)`). Defaults to `this.options` if not set.
486 * @return {Schema}
487 * @api public
488 */
489
490Schema.prototype.pick = function(paths, options) {
491 const newSchema = new Schema({}, options || this.options);
492 if (!Array.isArray(paths)) {
493 throw new MongooseError('Schema#pick() only accepts an array argument, ' +
494 'got "' + typeof paths + '"');
495 }
496
497 for (const path of paths) {
498 if (this.nested[path]) {
499 newSchema.add({ [path]: get(this.tree, path) });
500 } else {
501 const schematype = this.path(path);
502 if (schematype == null) {
503 throw new MongooseError('Path `' + path + '` is not in the schema');
504 }
505 newSchema.add({ [path]: schematype });
506 }
507 }
508
509 return newSchema;
510};
511
512/**
513 * Returns a new schema that has the `paths` from the original schema, minus the omitted ones.
514 *
515 * This method is analagous to [Lodash's `omit()` function](https://lodash.com/docs/#omit) for Mongoose schemas.
516 *
517 * #### Example:
518 *
519 * const schema = Schema({ name: String, age: Number });
520 * // Creates a new schema omitting the `age` path
521 * const newSchema = schema.omit(['age']);
522 *
523 * newSchema.path('name'); // SchemaString { ... }
524 * newSchema.path('age'); // undefined
525 *
526 * @param {String[]} paths List of Paths to omit for the new Schema
527 * @param {Object} [options] Options to pass to the new Schema Constructor (same as `new Schema(.., Options)`). Defaults to `this.options` if not set.
528 * @return {Schema}
529 * @api public
530 */
531
532Schema.prototype.omit = function(paths, options) {
533 const newSchema = new Schema(this, options || this.options);
534 if (!Array.isArray(paths)) {
535 throw new MongooseError(
536 'Schema#omit() only accepts an array argument, ' +
537 'got "' +
538 typeof paths +
539 '"'
540 );
541 }
542
543 newSchema.remove(paths);
544
545 for (const nested in newSchema.singleNestedPaths) {
546 if (paths.includes(nested)) {
547 delete newSchema.singleNestedPaths[nested];
548 }
549 }
550
551 return newSchema;
552};
553
554/**
555 * Returns default options for this schema, merged with `options`.
556 *
557 * @param {Object} [options] Options to overwrite the default options
558 * @return {Object} The merged options of `options` and the default options
559 * @api private
560 */
561
562Schema.prototype.defaultOptions = function(options) {
563 this._userProvidedOptions = options == null ? {} : clone(options);
564 const baseOptions = this.base && this.base.options || {};
565 const strict = 'strict' in baseOptions ? baseOptions.strict : true;
566 const strictQuery = 'strictQuery' in baseOptions ? baseOptions.strictQuery : false;
567 const id = 'id' in baseOptions ? baseOptions.id : true;
568 options = {
569 strict,
570 strictQuery,
571 bufferCommands: true,
572 capped: false, // { size, max, autoIndexId }
573 versionKey: '__v',
574 optimisticConcurrency: false,
575 minimize: true,
576 autoIndex: null,
577 discriminatorKey: '__t',
578 shardKey: null,
579 read: null,
580 validateBeforeSave: true,
581 validateModifiedOnly: false,
582 // the following are only applied at construction time
583 _id: true,
584 id: id,
585 typeKey: 'type',
586 ...options
587 };
588
589 if (options.versionKey && typeof options.versionKey !== 'string') {
590 throw new MongooseError('`versionKey` must be falsy or string, got `' + (typeof options.versionKey) + '`');
591 }
592
593 if (typeof options.read === 'string') {
594 options.read = handleReadPreferenceAliases(options.read);
595 } else if (Array.isArray(options.read) && typeof options.read[0] === 'string') {
596 options.read = {
597 mode: handleReadPreferenceAliases(options.read[0]),
598 tags: options.read[1]
599 };
600 }
601
602 if (options.optimisticConcurrency && !options.versionKey) {
603 throw new MongooseError('Must set `versionKey` if using `optimisticConcurrency`');
604 }
605
606 return options;
607};
608
609/**
610 * Inherit a Schema by applying a discriminator on an existing Schema.
611 *
612 *
613 * #### Example:
614 *
615 * const eventSchema = new mongoose.Schema({ timestamp: Date }, { discriminatorKey: 'kind' });
616 *
617 * const clickedEventSchema = new mongoose.Schema({ element: String }, { discriminatorKey: 'kind' });
618 * const ClickedModel = eventSchema.discriminator('clicked', clickedEventSchema);
619 *
620 * const Event = mongoose.model('Event', eventSchema);
621 *
622 * Event.discriminators['clicked']; // Model { clicked }
623 *
624 * const doc = await Event.create({ kind: 'clicked', element: '#hero' });
625 * doc.element; // '#hero'
626 * doc instanceof ClickedModel; // true
627 *
628 * @param {String} name the name of the discriminator
629 * @param {Schema} schema the discriminated Schema
630 * @param {Object} [options] discriminator options
631 * @param {String} [options.value] the string stored in the `discriminatorKey` property. If not specified, Mongoose uses the `name` parameter.
632 * @param {Boolean} [options.clone=true] By default, `discriminator()` clones the given `schema`. Set to `false` to skip cloning.
633 * @param {Boolean} [options.overwriteModels=false] by default, Mongoose does not allow you to define a discriminator with the same name as another discriminator. Set this to allow overwriting discriminators with the same name.
634 * @param {Boolean} [options.mergeHooks=true] By default, Mongoose merges the base schema's hooks with the discriminator schema's hooks. Set this option to `false` to make Mongoose use the discriminator schema's hooks instead.
635 * @param {Boolean} [options.mergePlugins=true] By default, Mongoose merges the base schema's plugins with the discriminator schema's plugins. Set this option to `false` to make Mongoose use the discriminator schema's plugins instead.
636 * @return {Schema} the Schema instance
637 * @api public
638 */
639Schema.prototype.discriminator = function(name, schema, options) {
640 this._applyDiscriminators = this._applyDiscriminators || new Map();
641 this._applyDiscriminators.set(name, { schema, options });
642
643 return this;
644};
645
646/*!
647 * Get this schema's default toObject/toJSON options, including Mongoose global
648 * options.
649 */
650
651Schema.prototype._defaultToObjectOptions = function(json) {
652 const path = json ? 'toJSON' : 'toObject';
653 if (this._defaultToObjectOptionsMap && this._defaultToObjectOptionsMap[path]) {
654 return this._defaultToObjectOptionsMap[path];
655 }
656
657 const baseOptions = this.base &&
658 this.base.options &&
659 this.base.options[path] || {};
660 const schemaOptions = this.options[path] || {};
661 // merge base default options with Schema's set default options if available.
662 // `clone` is necessary here because `utils.options` directly modifies the second input.
663 const defaultOptions = Object.assign({}, baseOptions, schemaOptions);
664
665 this._defaultToObjectOptionsMap = this._defaultToObjectOptionsMap || {};
666 this._defaultToObjectOptionsMap[path] = defaultOptions;
667 return defaultOptions;
668};
669
670/**
671 * Adds key path / schema type pairs to this schema.
672 *
673 * #### Example:
674 *
675 * const ToySchema = new Schema();
676 * ToySchema.add({ name: 'string', color: 'string', price: 'number' });
677 *
678 * const TurboManSchema = new Schema();
679 * // You can also `add()` another schema and copy over all paths, virtuals,
680 * // getters, setters, indexes, methods, and statics.
681 * TurboManSchema.add(ToySchema).add({ year: Number });
682 *
683 * @param {Object|Schema} obj plain object with paths to add, or another schema
684 * @param {String} [prefix] path to prefix the newly added paths with
685 * @return {Schema} the Schema instance
686 * @api public
687 */
688
689Schema.prototype.add = function add(obj, prefix) {
690 if (obj instanceof Schema || (obj != null && obj.instanceOfSchema)) {
691 merge(this, obj);
692
693 return this;
694 }
695
696 // Special case: setting top-level `_id` to false should convert to disabling
697 // the `_id` option. This behavior never worked before 5.4.11 but numerous
698 // codebases use it (see gh-7516, gh-7512).
699 if (obj._id === false && prefix == null) {
700 this.options._id = false;
701 }
702
703 prefix = prefix || '';
704 // avoid prototype pollution
705 if (prefix === '__proto__.' || prefix === 'constructor.' || prefix === 'prototype.') {
706 return this;
707 }
708
709 const keys = Object.keys(obj);
710 const typeKey = this.options.typeKey;
711 for (const key of keys) {
712 if (utils.specialProperties.has(key)) {
713 continue;
714 }
715
716 const fullPath = prefix + key;
717 const val = obj[key];
718
719 if (val == null) {
720 throw new TypeError('Invalid value for schema path `' + fullPath +
721 '`, got value "' + val + '"');
722 }
723 // Retain `_id: false` but don't set it as a path, re: gh-8274.
724 if (key === '_id' && val === false) {
725 continue;
726 }
727 // Deprecate setting schema paths to primitive types (gh-7558)
728 let isMongooseTypeString = false;
729 if (typeof val === 'string') {
730 // Handle the case in which the type is specified as a string (eg. 'date', 'oid', ...)
731 const MongooseTypes = this.base != null ? this.base.Schema.Types : Schema.Types;
732 const upperVal = val.charAt(0).toUpperCase() + val.substring(1);
733 isMongooseTypeString = MongooseTypes[upperVal] != null;
734 }
735 if (
736 key !== '_id' &&
737 ((typeof val !== 'object' && typeof val !== 'function' && !isMongooseTypeString) ||
738 val == null)
739 ) {
740 throw new TypeError(`Invalid schema configuration: \`${val}\` is not ` +
741 `a valid type at path \`${key}\`. See ` +
742 'https://bit.ly/mongoose-schematypes for a list of valid schema types.');
743 }
744 if (val instanceof VirtualType || (val.constructor && val.constructor.name || null) === 'VirtualType') {
745 this.virtual(val);
746 continue;
747 }
748
749 if (Array.isArray(val) && val.length === 1 && val[0] == null) {
750 throw new TypeError('Invalid value for schema Array path `' + fullPath +
751 '`, got value "' + val[0] + '"');
752 }
753
754 if (!(isPOJO(val) || val instanceof SchemaTypeOptions)) {
755 // Special-case: Non-options definitely a path so leaf at this node
756 // Examples: Schema instances, SchemaType instances
757 if (prefix) {
758 this.nested[prefix.substring(0, prefix.length - 1)] = true;
759 }
760 this.path(prefix + key, val);
761 if (val[0] != null && !(val[0].instanceOfSchema) && utils.isPOJO(val[0].discriminators)) {
762 const schemaType = this.path(prefix + key);
763 for (const key in val[0].discriminators) {
764 schemaType.discriminator(key, val[0].discriminators[key]);
765 }
766 }
767 } else if (Object.keys(val).length < 1) {
768 // Special-case: {} always interpreted as Mixed path so leaf at this node
769 if (prefix) {
770 this.nested[prefix.substring(0, prefix.length - 1)] = true;
771 }
772 this.path(fullPath, val); // mixed type
773 } else if (!val[typeKey] || (typeKey === 'type' && isPOJO(val.type) && val.type.type)) {
774 // Special-case: POJO with no bona-fide type key - interpret as tree of deep paths so recurse
775 // nested object `{ last: { name: String } }`. Avoid functions with `.type` re: #10807 because
776 // NestJS sometimes adds `Date.type`.
777 this.nested[fullPath] = true;
778 this.add(val, fullPath + '.');
779 } else {
780 // There IS a bona-fide type key that may also be a POJO
781 const _typeDef = val[typeKey];
782 if (isPOJO(_typeDef) && Object.keys(_typeDef).length > 0) {
783 // If a POJO is the value of a type key, make it a subdocument
784 if (prefix) {
785 this.nested[prefix.substring(0, prefix.length - 1)] = true;
786 }
787
788 const childSchemaOptions = {};
789 if (this._userProvidedOptions.typeKey) {
790 childSchemaOptions.typeKey = this._userProvidedOptions.typeKey;
791 }
792 // propagate 'strict' option to child schema
793 if (this._userProvidedOptions.strict != null) {
794 childSchemaOptions.strict = this._userProvidedOptions.strict;
795 }
796 if (this._userProvidedOptions.toObject != null) {
797 childSchemaOptions.toObject = utils.omit(this._userProvidedOptions.toObject, ['transform']);
798 }
799 if (this._userProvidedOptions.toJSON != null) {
800 childSchemaOptions.toJSON = utils.omit(this._userProvidedOptions.toJSON, ['transform']);
801 }
802
803 const _schema = new Schema(_typeDef, childSchemaOptions);
804 _schema.$implicitlyCreated = true;
805 const schemaWrappedPath = Object.assign({}, val, { [typeKey]: _schema });
806 this.path(prefix + key, schemaWrappedPath);
807 } else {
808 // Either the type is non-POJO or we interpret it as Mixed anyway
809 if (prefix) {
810 this.nested[prefix.substring(0, prefix.length - 1)] = true;
811 }
812 this.path(prefix + key, val);
813 if (val != null && !(val.instanceOfSchema) && utils.isPOJO(val.discriminators)) {
814 const schemaType = this.path(prefix + key);
815 for (const key in val.discriminators) {
816 schemaType.discriminator(key, val.discriminators[key]);
817 }
818 }
819 }
820 }
821 }
822
823 const aliasObj = Object.fromEntries(
824 Object.entries(obj).map(([key]) => ([prefix + key, null]))
825 );
826 aliasFields(this, aliasObj);
827 return this;
828};
829
830/**
831 * Add an alias for `path`. This means getting or setting the `alias`
832 * is equivalent to getting or setting the `path`.
833 *
834 * #### Example:
835 *
836 * const toySchema = new Schema({ n: String });
837 *
838 * // Make 'name' an alias for 'n'
839 * toySchema.alias('n', 'name');
840 *
841 * const Toy = mongoose.model('Toy', toySchema);
842 * const turboMan = new Toy({ n: 'Turbo Man' });
843 *
844 * turboMan.name; // 'Turbo Man'
845 * turboMan.n; // 'Turbo Man'
846 *
847 * turboMan.name = 'Turbo Man Action Figure';
848 * turboMan.n; // 'Turbo Man Action Figure'
849 *
850 * await turboMan.save(); // Saves { _id: ..., n: 'Turbo Man Action Figure' }
851 *
852 *
853 * @param {String} path real path to alias
854 * @param {String|String[]} alias the path(s) to use as an alias for `path`
855 * @return {Schema} the Schema instance
856 * @api public
857 */
858
859Schema.prototype.alias = function alias(path, alias) {
860 aliasFields(this, { [path]: alias });
861 return this;
862};
863
864/**
865 * Remove an index by name or index specification.
866 *
867 * removeIndex only removes indexes from your schema object. Does **not** affect the indexes
868 * in MongoDB.
869 *
870 * #### Example:
871 *
872 * const ToySchema = new Schema({ name: String, color: String, price: Number });
873 *
874 * // Add a new index on { name, color }
875 * ToySchema.index({ name: 1, color: 1 });
876 *
877 * // Remove index on { name, color }
878 * // Keep in mind that order matters! `removeIndex({ color: 1, name: 1 })` won't remove the index
879 * ToySchema.removeIndex({ name: 1, color: 1 });
880 *
881 * // Add an index with a custom name
882 * ToySchema.index({ color: 1 }, { name: 'my custom index name' });
883 * // Remove index by name
884 * ToySchema.removeIndex('my custom index name');
885 *
886 * @param {Object|string} index name or index specification
887 * @return {Schema} the Schema instance
888 * @api public
889 */
890
891Schema.prototype.removeIndex = function removeIndex(index) {
892 if (arguments.length > 1) {
893 throw new Error('removeIndex() takes only 1 argument');
894 }
895
896 if (typeof index !== 'object' && typeof index !== 'string') {
897 throw new Error('removeIndex() may only take either an object or a string as an argument');
898 }
899
900 if (typeof index === 'object') {
901 for (let i = this._indexes.length - 1; i >= 0; --i) {
902 if (util.isDeepStrictEqual(this._indexes[i][0], index)) {
903 this._indexes.splice(i, 1);
904 }
905 }
906 } else {
907 for (let i = this._indexes.length - 1; i >= 0; --i) {
908 if (this._indexes[i][1] != null && this._indexes[i][1].name === index) {
909 this._indexes.splice(i, 1);
910 }
911 }
912 }
913
914 return this;
915};
916
917/**
918 * Remove all indexes from this schema.
919 *
920 * clearIndexes only removes indexes from your schema object. Does **not** affect the indexes
921 * in MongoDB.
922 *
923 * #### Example:
924 *
925 * const ToySchema = new Schema({ name: String, color: String, price: Number });
926 * ToySchema.index({ name: 1 });
927 * ToySchema.index({ color: 1 });
928 *
929 * // Remove all indexes on this schema
930 * ToySchema.clearIndexes();
931 *
932 * ToySchema.indexes(); // []
933 *
934 * @return {Schema} the Schema instance
935 * @api public
936 */
937
938Schema.prototype.clearIndexes = function clearIndexes() {
939 this._indexes.length = 0;
940
941 return this;
942};
943
944/**
945 * Add an [Atlas search index](https://www.mongodb.com/docs/atlas/atlas-search/create-index/) that Mongoose will create using `Model.createSearchIndex()`.
946 * This function only works when connected to MongoDB Atlas.
947 *
948 * #### Example:
949 *
950 * const ToySchema = new Schema({ name: String, color: String, price: Number });
951 * ToySchema.searchIndex({ name: 'test', definition: { mappings: { dynamic: true } } });
952 *
953 * @param {Object} description index options, including `name` and `definition`
954 * @param {String} description.name
955 * @param {Object} description.definition
956 * @return {Schema} the Schema instance
957 * @api public
958 */
959
960Schema.prototype.searchIndex = function searchIndex(description) {
961 this._searchIndexes.push(description);
962
963 return this;
964};
965
966/**
967 * Reserved document keys.
968 *
969 * Keys in this object are names that are warned in schema declarations
970 * because they have the potential to break Mongoose/ Mongoose plugins functionality. If you create a schema
971 * using `new Schema()` with one of these property names, Mongoose will log a warning.
972 *
973 * - _posts
974 * - _pres
975 * - collection
976 * - emit
977 * - errors
978 * - get
979 * - init
980 * - isModified
981 * - isNew
982 * - listeners
983 * - modelName
984 * - on
985 * - once
986 * - populated
987 * - prototype
988 * - remove
989 * - removeListener
990 * - save
991 * - schema
992 * - toObject
993 * - validate
994 *
995 * _NOTE:_ Use of these terms as method names is permitted, but play at your own risk, as they may be existing mongoose document methods you are stomping on.
996 *
997 * const schema = new Schema(..);
998 * schema.methods.init = function () {} // potentially breaking
999 *
1000 * @property reserved
1001 * @memberOf Schema
1002 * @static
1003 */
1004
1005Schema.reserved = Object.create(null);
1006Schema.prototype.reserved = Schema.reserved;
1007
1008const reserved = Schema.reserved;
1009// Core object
1010reserved['prototype'] =
1011// EventEmitter
1012reserved.emit =
1013reserved.listeners =
1014reserved.removeListener =
1015
1016// document properties and functions
1017reserved.collection =
1018reserved.errors =
1019reserved.get =
1020reserved.init =
1021reserved.isModified =
1022reserved.isNew =
1023reserved.populated =
1024reserved.remove =
1025reserved.save =
1026reserved.toObject =
1027reserved.validate = 1;
1028reserved.collection = 1;
1029
1030/**
1031 * Gets/sets schema paths.
1032 *
1033 * Sets a path (if arity 2)
1034 * Gets a path (if arity 1)
1035 *
1036 * #### Example:
1037 *
1038 * schema.path('name') // returns a SchemaType
1039 * schema.path('name', Number) // changes the schemaType of `name` to Number
1040 *
1041 * @param {String} path The name of the Path to get / set
1042 * @param {Object} [obj] The Type to set the path to, if provided the path will be SET, otherwise the path will be GET
1043 * @api public
1044 */
1045
1046Schema.prototype.path = function(path, obj) {
1047 if (obj === undefined) {
1048 if (this.paths[path] != null) {
1049 return this.paths[path];
1050 }
1051 // Convert to '.$' to check subpaths re: gh-6405
1052 const cleanPath = _pathToPositionalSyntax(path);
1053 let schematype = _getPath(this, path, cleanPath);
1054 if (schematype != null) {
1055 return schematype;
1056 }
1057
1058 // Look for maps
1059 const mapPath = getMapPath(this, path);
1060 if (mapPath != null) {
1061 return mapPath;
1062 }
1063
1064 // Look if a parent of this path is mixed
1065 schematype = this.hasMixedParent(cleanPath);
1066 if (schematype != null) {
1067 return schematype;
1068 }
1069
1070 // subpaths?
1071 return hasNumericSubpathRegex.test(path)
1072 ? getPositionalPath(this, path, cleanPath)
1073 : undefined;
1074 }
1075
1076 // some path names conflict with document methods
1077 const firstPieceOfPath = path.split('.')[0];
1078 if (reserved[firstPieceOfPath] && !this.options.suppressReservedKeysWarning) {
1079 const errorMessage = `\`${firstPieceOfPath}\` is a reserved schema pathname and may break some functionality. ` +
1080 'You are allowed to use it, but use at your own risk. ' +
1081 'To disable this warning pass `suppressReservedKeysWarning` as a schema option.';
1082
1083 utils.warn(errorMessage);
1084 }
1085
1086 if (typeof obj === 'object' && utils.hasUserDefinedProperty(obj, 'ref')) {
1087 validateRef(obj.ref, path);
1088 }
1089
1090 // update the tree
1091 const subpaths = path.split(/\./);
1092 const last = subpaths.pop();
1093 let branch = this.tree;
1094 let fullPath = '';
1095
1096 for (const sub of subpaths) {
1097 if (utils.specialProperties.has(sub)) {
1098 throw new Error('Cannot set special property `' + sub + '` on a schema');
1099 }
1100 fullPath = fullPath += (fullPath.length > 0 ? '.' : '') + sub;
1101 if (!branch[sub]) {
1102 this.nested[fullPath] = true;
1103 branch[sub] = {};
1104 }
1105 if (typeof branch[sub] !== 'object') {
1106 const msg = 'Cannot set nested path `' + path + '`. '
1107 + 'Parent path `'
1108 + fullPath
1109 + '` already set to type ' + branch[sub].name
1110 + '.';
1111 throw new Error(msg);
1112 }
1113 branch = branch[sub];
1114 }
1115
1116 branch[last] = clone(obj);
1117
1118 this.paths[path] = this.interpretAsType(path, obj, this.options);
1119 const schemaType = this.paths[path];
1120
1121 if (schemaType.$isSchemaMap) {
1122 // Maps can have arbitrary keys, so `$*` is internal shorthand for "any key"
1123 // The '$' is to imply this path should never be stored in MongoDB so we
1124 // can easily build a regexp out of this path, and '*' to imply "any key."
1125 const mapPath = path + '.$*';
1126
1127 this.paths[mapPath] = schemaType.$__schemaType;
1128 this.mapPaths.push(this.paths[mapPath]);
1129 }
1130
1131 if (schemaType.$isSingleNested) {
1132 for (const key of Object.keys(schemaType.schema.paths)) {
1133 this.singleNestedPaths[path + '.' + key] = schemaType.schema.paths[key];
1134 }
1135 for (const key of Object.keys(schemaType.schema.singleNestedPaths)) {
1136 this.singleNestedPaths[path + '.' + key] =
1137 schemaType.schema.singleNestedPaths[key];
1138 }
1139 for (const key of Object.keys(schemaType.schema.subpaths)) {
1140 this.singleNestedPaths[path + '.' + key] =
1141 schemaType.schema.subpaths[key];
1142 }
1143 for (const key of Object.keys(schemaType.schema.nested)) {
1144 this.singleNestedPaths[path + '.' + key] = 'nested';
1145 }
1146
1147 Object.defineProperty(schemaType.schema, 'base', {
1148 configurable: true,
1149 enumerable: false,
1150 writable: false,
1151 value: this.base
1152 });
1153
1154 schemaType.caster.base = this.base;
1155 this.childSchemas.push({
1156 schema: schemaType.schema,
1157 model: schemaType.caster
1158 });
1159 } else if (schemaType.$isMongooseDocumentArray) {
1160 Object.defineProperty(schemaType.schema, 'base', {
1161 configurable: true,
1162 enumerable: false,
1163 writable: false,
1164 value: this.base
1165 });
1166
1167 schemaType.casterConstructor.base = this.base;
1168 this.childSchemas.push({
1169 schema: schemaType.schema,
1170 model: schemaType.casterConstructor
1171 });
1172 }
1173
1174 if (schemaType.$isMongooseArray && schemaType.caster instanceof SchemaType) {
1175 let arrayPath = path;
1176 let _schemaType = schemaType;
1177
1178 const toAdd = [];
1179 while (_schemaType.$isMongooseArray) {
1180 arrayPath = arrayPath + '.$';
1181
1182 // Skip arrays of document arrays
1183 if (_schemaType.$isMongooseDocumentArray) {
1184 _schemaType.$embeddedSchemaType._arrayPath = arrayPath;
1185 _schemaType.$embeddedSchemaType._arrayParentPath = path;
1186 _schemaType = _schemaType.$embeddedSchemaType;
1187 } else {
1188 _schemaType.caster._arrayPath = arrayPath;
1189 _schemaType.caster._arrayParentPath = path;
1190 _schemaType = _schemaType.caster;
1191 }
1192
1193 this.subpaths[arrayPath] = _schemaType;
1194 }
1195
1196 for (const _schemaType of toAdd) {
1197 this.subpaths[_schemaType.path] = _schemaType;
1198 }
1199 }
1200
1201 if (schemaType.$isMongooseDocumentArray) {
1202 for (const key of Object.keys(schemaType.schema.paths)) {
1203 const _schemaType = schemaType.schema.paths[key];
1204 this.subpaths[path + '.' + key] = _schemaType;
1205 if (typeof _schemaType === 'object' && _schemaType != null && _schemaType.$parentSchemaDocArray == null) {
1206 _schemaType.$parentSchemaDocArray = schemaType;
1207 }
1208 }
1209 for (const key of Object.keys(schemaType.schema.subpaths)) {
1210 const _schemaType = schemaType.schema.subpaths[key];
1211 this.subpaths[path + '.' + key] = _schemaType;
1212 if (typeof _schemaType === 'object' && _schemaType != null && _schemaType.$parentSchemaDocArray == null) {
1213 _schemaType.$parentSchemaDocArray = schemaType;
1214 }
1215 }
1216 for (const key of Object.keys(schemaType.schema.singleNestedPaths)) {
1217 const _schemaType = schemaType.schema.singleNestedPaths[key];
1218 this.subpaths[path + '.' + key] = _schemaType;
1219 if (typeof _schemaType === 'object' && _schemaType != null && _schemaType.$parentSchemaDocArray == null) {
1220 _schemaType.$parentSchemaDocArray = schemaType;
1221 }
1222 }
1223 }
1224
1225 return this;
1226};
1227
1228/*!
1229 * ignore
1230 */
1231
1232function gatherChildSchemas(schema) {
1233 const childSchemas = [];
1234
1235 for (const path of Object.keys(schema.paths)) {
1236 const schematype = schema.paths[path];
1237 if (schematype.$isMongooseDocumentArray || schematype.$isSingleNested) {
1238 childSchemas.push({ schema: schematype.schema, model: schematype.caster });
1239 }
1240 }
1241
1242 return childSchemas;
1243}
1244
1245/*!
1246 * ignore
1247 */
1248
1249function _getPath(schema, path, cleanPath) {
1250 if (schema.paths.hasOwnProperty(path)) {
1251 return schema.paths[path];
1252 }
1253 if (schema.subpaths.hasOwnProperty(cleanPath)) {
1254 const subpath = schema.subpaths[cleanPath];
1255 if (subpath === 'nested') {
1256 return undefined;
1257 }
1258 return subpath;
1259 }
1260 if (schema.singleNestedPaths.hasOwnProperty(cleanPath) && typeof schema.singleNestedPaths[cleanPath] === 'object') {
1261 const singleNestedPath = schema.singleNestedPaths[cleanPath];
1262 if (singleNestedPath === 'nested') {
1263 return undefined;
1264 }
1265 return singleNestedPath;
1266 }
1267
1268 return null;
1269}
1270
1271/*!
1272 * ignore
1273 */
1274
1275function _pathToPositionalSyntax(path) {
1276 if (!/\.\d+/.test(path)) {
1277 return path;
1278 }
1279 return path.replace(/\.\d+\./g, '.$.').replace(/\.\d+$/, '.$');
1280}
1281
1282/*!
1283 * ignore
1284 */
1285
1286function getMapPath(schema, path) {
1287 if (schema.mapPaths.length === 0) {
1288 return null;
1289 }
1290 for (const val of schema.mapPaths) {
1291 const _path = val.path;
1292 const re = new RegExp('^' + _path.replace(/\.\$\*/g, '\\.[^.]+') + '$');
1293 if (re.test(path)) {
1294 return schema.paths[_path];
1295 }
1296 }
1297
1298 return null;
1299}
1300
1301/**
1302 * The Mongoose instance this schema is associated with
1303 *
1304 * @property base
1305 * @api private
1306 */
1307
1308Object.defineProperty(Schema.prototype, 'base', {
1309 configurable: true,
1310 enumerable: false,
1311 writable: true,
1312 value: null
1313});
1314
1315/**
1316 * Converts type arguments into Mongoose Types.
1317 *
1318 * @param {String} path
1319 * @param {Object} obj constructor
1320 * @param {Object} options
1321 * @api private
1322 */
1323
1324Schema.prototype.interpretAsType = function(path, obj, options) {
1325 if (obj instanceof SchemaType) {
1326 if (obj.path === path) {
1327 return obj;
1328 }
1329 const clone = obj.clone();
1330 clone.path = path;
1331 return clone;
1332 }
1333
1334
1335 // If this schema has an associated Mongoose object, use the Mongoose object's
1336 // copy of SchemaTypes re: gh-7158 gh-6933
1337 const MongooseTypes = this.base != null ? this.base.Schema.Types : Schema.Types;
1338 const Types = this.base != null ? this.base.Types : require('./types');
1339
1340 if (!utils.isPOJO(obj) && !(obj instanceof SchemaTypeOptions)) {
1341 const constructorName = utils.getFunctionName(obj.constructor);
1342 if (constructorName !== 'Object') {
1343 const oldObj = obj;
1344 obj = {};
1345 obj[options.typeKey] = oldObj;
1346 }
1347 }
1348
1349 // Get the type making sure to allow keys named "type"
1350 // and default to mixed if not specified.
1351 // { type: { type: String, default: 'freshcut' } }
1352 let type = obj[options.typeKey] && (obj[options.typeKey] instanceof Function || options.typeKey !== 'type' || !obj.type.type)
1353 ? obj[options.typeKey]
1354 : {};
1355 let name;
1356
1357 if (utils.isPOJO(type) || type === 'mixed') {
1358 return new MongooseTypes.Mixed(path, obj);
1359 }
1360
1361 if (Array.isArray(type) || type === Array || type === 'array' || type === MongooseTypes.Array) {
1362 // if it was specified through { type } look for `cast`
1363 let cast = (type === Array || type === 'array')
1364 ? obj.cast || obj.of
1365 : type[0];
1366
1367 // new Schema({ path: [new Schema({ ... })] })
1368 if (cast && cast.instanceOfSchema) {
1369 if (!(cast instanceof Schema)) {
1370 if (this.options._isMerging) {
1371 cast = new Schema(cast);
1372 } else {
1373 throw new TypeError('Schema for array path `' + path +
1374 '` is from a different copy of the Mongoose module. ' +
1375 'Please make sure you\'re using the same version ' +
1376 'of Mongoose everywhere with `npm list mongoose`. If you are still ' +
1377 'getting this error, please add `new Schema()` around the path: ' +
1378 `${path}: new Schema(...)`);
1379 }
1380 }
1381 return new MongooseTypes.DocumentArray(path, cast, obj);
1382 }
1383 if (cast &&
1384 cast[options.typeKey] &&
1385 cast[options.typeKey].instanceOfSchema) {
1386 if (!(cast[options.typeKey] instanceof Schema)) {
1387 if (this.options._isMerging) {
1388 cast[options.typeKey] = new Schema(cast[options.typeKey]);
1389 } else {
1390 throw new TypeError('Schema for array path `' + path +
1391 '` is from a different copy of the Mongoose module. ' +
1392 'Please make sure you\'re using the same version ' +
1393 'of Mongoose everywhere with `npm list mongoose`. If you are still ' +
1394 'getting this error, please add `new Schema()` around the path: ' +
1395 `${path}: new Schema(...)`);
1396 }
1397 }
1398 return new MongooseTypes.DocumentArray(path, cast[options.typeKey], obj, cast);
1399 }
1400 if (typeof cast !== 'undefined') {
1401 if (Array.isArray(cast) || cast.type === Array || cast.type == 'Array') {
1402 if (cast && cast.type == 'Array') {
1403 cast.type = Array;
1404 }
1405 return new MongooseTypes.Array(path, this.interpretAsType(path, cast, options), obj);
1406 }
1407 }
1408
1409 // Handle both `new Schema({ arr: [{ subpath: String }] })` and `new Schema({ arr: [{ type: { subpath: string } }] })`
1410 const castFromTypeKey = (cast != null && cast[options.typeKey] && (options.typeKey !== 'type' || !cast.type.type)) ?
1411 cast[options.typeKey] :
1412 cast;
1413 if (typeof cast === 'string') {
1414 cast = MongooseTypes[cast.charAt(0).toUpperCase() + cast.substring(1)];
1415 } else if (utils.isPOJO(castFromTypeKey)) {
1416 if (Object.keys(castFromTypeKey).length) {
1417 // The `minimize` and `typeKey` options propagate to child schemas
1418 // declared inline, like `{ arr: [{ val: { $type: String } }] }`.
1419 // See gh-3560
1420 const childSchemaOptions = { minimize: options.minimize };
1421 if (options.typeKey) {
1422 childSchemaOptions.typeKey = options.typeKey;
1423 }
1424 // propagate 'strict' option to child schema
1425 if (options.hasOwnProperty('strict')) {
1426 childSchemaOptions.strict = options.strict;
1427 }
1428 if (options.hasOwnProperty('strictQuery')) {
1429 childSchemaOptions.strictQuery = options.strictQuery;
1430 }
1431 if (options.hasOwnProperty('toObject')) {
1432 childSchemaOptions.toObject = utils.omit(options.toObject, ['transform']);
1433 }
1434 if (options.hasOwnProperty('toJSON')) {
1435 childSchemaOptions.toJSON = utils.omit(options.toJSON, ['transform']);
1436 }
1437
1438 if (this._userProvidedOptions.hasOwnProperty('_id')) {
1439 childSchemaOptions._id = this._userProvidedOptions._id;
1440 } else if (Schema.Types.DocumentArray.defaultOptions._id != null) {
1441 childSchemaOptions._id = Schema.Types.DocumentArray.defaultOptions._id;
1442 }
1443
1444 const childSchema = new Schema(castFromTypeKey, childSchemaOptions);
1445 childSchema.$implicitlyCreated = true;
1446 return new MongooseTypes.DocumentArray(path, childSchema, obj);
1447 } else {
1448 // Special case: empty object becomes mixed
1449 return new MongooseTypes.Array(path, MongooseTypes.Mixed, obj);
1450 }
1451 }
1452
1453 if (cast) {
1454 type = cast[options.typeKey] && (options.typeKey !== 'type' || !cast.type.type)
1455 ? cast[options.typeKey]
1456 : cast;
1457 if (Array.isArray(type)) {
1458 return new MongooseTypes.Array(path, this.interpretAsType(path, type, options), obj);
1459 }
1460
1461 name = typeof type === 'string'
1462 ? type
1463 : type.schemaName || utils.getFunctionName(type);
1464
1465 // For Jest 26+, see #10296
1466 if (name === 'ClockDate') {
1467 name = 'Date';
1468 }
1469
1470 if (name === void 0) {
1471 throw new TypeError('Invalid schema configuration: ' +
1472 `Could not determine the embedded type for array \`${path}\`. ` +
1473 'See https://mongoosejs.com/docs/guide.html#definition for more info on supported schema syntaxes.');
1474 }
1475 if (!MongooseTypes.hasOwnProperty(name)) {
1476 throw new TypeError('Invalid schema configuration: ' +
1477 `\`${name}\` is not a valid type within the array \`${path}\`.` +
1478 'See https://bit.ly/mongoose-schematypes for a list of valid schema types.');
1479 }
1480 }
1481
1482 return new MongooseTypes.Array(path, cast || MongooseTypes.Mixed, obj, options);
1483 }
1484
1485 if (type && type.instanceOfSchema) {
1486 return new MongooseTypes.Subdocument(type, path, obj);
1487 }
1488
1489 if (Buffer.isBuffer(type)) {
1490 name = 'Buffer';
1491 } else if (typeof type === 'function' || typeof type === 'object') {
1492 name = type.schemaName || utils.getFunctionName(type);
1493 } else if (type === Types.ObjectId) {
1494 name = 'ObjectId';
1495 } else if (type === Types.Decimal128) {
1496 name = 'Decimal128';
1497 } else {
1498 name = type == null ? '' + type : type.toString();
1499 }
1500
1501 if (name) {
1502 name = name.charAt(0).toUpperCase() + name.substring(1);
1503 }
1504 // Special case re: gh-7049 because the bson `ObjectID` class' capitalization
1505 // doesn't line up with Mongoose's.
1506 if (name === 'ObjectID') {
1507 name = 'ObjectId';
1508 }
1509 // For Jest 26+, see #10296
1510 if (name === 'ClockDate') {
1511 name = 'Date';
1512 }
1513
1514 if (name === void 0) {
1515 throw new TypeError(`Invalid schema configuration: \`${path}\` schematype definition is ` +
1516 'invalid. See ' +
1517 'https://mongoosejs.com/docs/guide.html#definition for more info on supported schema syntaxes.');
1518 }
1519 if (MongooseTypes[name] == null) {
1520 throw new TypeError(`Invalid schema configuration: \`${name}\` is not ` +
1521 `a valid type at path \`${path}\`. See ` +
1522 'https://bit.ly/mongoose-schematypes for a list of valid schema types.');
1523 }
1524
1525 const schemaType = new MongooseTypes[name](path, obj);
1526
1527 if (schemaType.$isSchemaMap) {
1528 createMapNestedSchemaType(this, schemaType, path, obj, options);
1529 }
1530
1531 return schemaType;
1532};
1533
1534/*!
1535 * ignore
1536 */
1537
1538function createMapNestedSchemaType(schema, schemaType, path, obj, options) {
1539 const mapPath = path + '.$*';
1540 let _mapType = { type: {} };
1541 if (utils.hasUserDefinedProperty(obj, 'of')) {
1542 const isInlineSchema = utils.isPOJO(obj.of) &&
1543 Object.keys(obj.of).length > 0 &&
1544 !utils.hasUserDefinedProperty(obj.of, schema.options.typeKey);
1545 if (isInlineSchema) {
1546 _mapType = { [schema.options.typeKey]: new Schema(obj.of) };
1547 } else if (utils.isPOJO(obj.of)) {
1548 _mapType = Object.assign({}, obj.of);
1549 } else {
1550 _mapType = { [schema.options.typeKey]: obj.of };
1551 }
1552
1553 if (_mapType[schema.options.typeKey] && _mapType[schema.options.typeKey].instanceOfSchema) {
1554 const subdocumentSchema = _mapType[schema.options.typeKey];
1555 subdocumentSchema.eachPath((subpath, type) => {
1556 if (type.options.select === true || type.options.select === false) {
1557 throw new MongooseError('Cannot use schema-level projections (`select: true` or `select: false`) within maps at path "' + path + '.' + subpath + '"');
1558 }
1559 });
1560 }
1561
1562 if (utils.hasUserDefinedProperty(obj, 'ref')) {
1563 _mapType.ref = obj.ref;
1564 }
1565 }
1566 schemaType.$__schemaType = schema.interpretAsType(mapPath, _mapType, options);
1567}
1568
1569/**
1570 * Iterates the schemas paths similar to Array#forEach.
1571 *
1572 * The callback is passed the pathname and the schemaType instance.
1573 *
1574 * #### Example:
1575 *
1576 * const userSchema = new Schema({ name: String, registeredAt: Date });
1577 * userSchema.eachPath((pathname, schematype) => {
1578 * // Prints twice:
1579 * // name SchemaString { ... }
1580 * // registeredAt SchemaDate { ... }
1581 * console.log(pathname, schematype);
1582 * });
1583 *
1584 * @param {Function} fn callback function
1585 * @return {Schema} this
1586 * @api public
1587 */
1588
1589Schema.prototype.eachPath = function(fn) {
1590 const keys = Object.keys(this.paths);
1591 const len = keys.length;
1592
1593 for (let i = 0; i < len; ++i) {
1594 fn(keys[i], this.paths[keys[i]]);
1595 }
1596
1597 return this;
1598};
1599
1600/**
1601 * Returns an Array of path strings that are required by this schema.
1602 *
1603 * #### Example:
1604 *
1605 * const s = new Schema({
1606 * name: { type: String, required: true },
1607 * age: { type: String, required: true },
1608 * notes: String
1609 * });
1610 * s.requiredPaths(); // [ 'age', 'name' ]
1611 *
1612 * @api public
1613 * @param {Boolean} invalidate Refresh the cache
1614 * @return {Array}
1615 */
1616
1617Schema.prototype.requiredPaths = function requiredPaths(invalidate) {
1618 if (this._requiredpaths && !invalidate) {
1619 return this._requiredpaths;
1620 }
1621
1622 const paths = Object.keys(this.paths);
1623 let i = paths.length;
1624 const ret = [];
1625
1626 while (i--) {
1627 const path = paths[i];
1628 if (this.paths[path].isRequired) {
1629 ret.push(path);
1630 }
1631 }
1632 this._requiredpaths = ret;
1633 return this._requiredpaths;
1634};
1635
1636/**
1637 * Returns indexes from fields and schema-level indexes (cached).
1638 *
1639 * @api private
1640 * @return {Array}
1641 */
1642
1643Schema.prototype.indexedPaths = function indexedPaths() {
1644 if (this._indexedpaths) {
1645 return this._indexedpaths;
1646 }
1647 this._indexedpaths = this.indexes();
1648 return this._indexedpaths;
1649};
1650
1651/**
1652 * Returns the pathType of `path` for this schema.
1653 *
1654 * Given a path, returns whether it is a real, virtual, nested, or ad-hoc/undefined path.
1655 *
1656 * #### Example:
1657 *
1658 * const s = new Schema({ name: String, nested: { foo: String } });
1659 * s.virtual('foo').get(() => 42);
1660 * s.pathType('name'); // "real"
1661 * s.pathType('nested'); // "nested"
1662 * s.pathType('foo'); // "virtual"
1663 * s.pathType('fail'); // "adhocOrUndefined"
1664 *
1665 * @param {String} path
1666 * @return {String}
1667 * @api public
1668 */
1669
1670Schema.prototype.pathType = function(path) {
1671 if (this.paths.hasOwnProperty(path)) {
1672 return 'real';
1673 }
1674 if (this.virtuals.hasOwnProperty(path)) {
1675 return 'virtual';
1676 }
1677 if (this.nested.hasOwnProperty(path)) {
1678 return 'nested';
1679 }
1680
1681 // Convert to '.$' to check subpaths re: gh-6405
1682 const cleanPath = _pathToPositionalSyntax(path);
1683
1684 if (this.subpaths.hasOwnProperty(cleanPath) || this.subpaths.hasOwnProperty(path)) {
1685 return 'real';
1686 }
1687
1688 const singleNestedPath = this.singleNestedPaths.hasOwnProperty(cleanPath) || this.singleNestedPaths.hasOwnProperty(path);
1689 if (singleNestedPath) {
1690 return singleNestedPath === 'nested' ? 'nested' : 'real';
1691 }
1692
1693 // Look for maps
1694 const mapPath = getMapPath(this, path);
1695 if (mapPath != null) {
1696 return 'real';
1697 }
1698
1699 if (/\.\d+\.|\.\d+$/.test(path)) {
1700 return getPositionalPathType(this, path, cleanPath);
1701 }
1702 return 'adhocOrUndefined';
1703};
1704
1705/**
1706 * Returns true iff this path is a child of a mixed schema.
1707 *
1708 * @param {String} path
1709 * @return {Boolean}
1710 * @api private
1711 */
1712
1713Schema.prototype.hasMixedParent = function(path) {
1714 const subpaths = path.split(/\./g);
1715 path = '';
1716 for (let i = 0; i < subpaths.length; ++i) {
1717 path = i > 0 ? path + '.' + subpaths[i] : subpaths[i];
1718 if (this.paths.hasOwnProperty(path) &&
1719 this.paths[path] instanceof MongooseTypes.Mixed) {
1720 return this.paths[path];
1721 }
1722 }
1723
1724 return null;
1725};
1726
1727/**
1728 * Setup updatedAt and createdAt timestamps to documents if enabled
1729 *
1730 * @param {Boolean|Object} timestamps timestamps options
1731 * @api private
1732 */
1733Schema.prototype.setupTimestamp = function(timestamps) {
1734 return setupTimestamps(this, timestamps);
1735};
1736
1737/**
1738 * ignore. Deprecated re: #6405
1739 * @param {Any} self
1740 * @param {String} path
1741 * @api private
1742 */
1743
1744function getPositionalPathType(self, path, cleanPath) {
1745 const subpaths = path.split(/\.(\d+)\.|\.(\d+)$/).filter(Boolean);
1746 if (subpaths.length < 2) {
1747 return self.paths.hasOwnProperty(subpaths[0]) ?
1748 self.paths[subpaths[0]] :
1749 'adhocOrUndefined';
1750 }
1751
1752 let val = self.path(subpaths[0]);
1753 let isNested = false;
1754 if (!val) {
1755 return 'adhocOrUndefined';
1756 }
1757
1758 const last = subpaths.length - 1;
1759
1760 for (let i = 1; i < subpaths.length; ++i) {
1761 isNested = false;
1762 const subpath = subpaths[i];
1763
1764 if (i === last && val && !/\D/.test(subpath)) {
1765 if (val.$isMongooseDocumentArray) {
1766 val = val.$embeddedSchemaType;
1767 } else if (val instanceof MongooseTypes.Array) {
1768 // StringSchema, NumberSchema, etc
1769 val = val.caster;
1770 } else {
1771 val = undefined;
1772 }
1773 break;
1774 }
1775
1776 // ignore if its just a position segment: path.0.subpath
1777 if (!/\D/.test(subpath)) {
1778 // Nested array
1779 if (val instanceof MongooseTypes.Array && i !== last) {
1780 val = val.caster;
1781 }
1782 continue;
1783 }
1784
1785 if (!(val && val.schema)) {
1786 val = undefined;
1787 break;
1788 }
1789
1790 const type = val.schema.pathType(subpath);
1791 isNested = (type === 'nested');
1792 val = val.schema.path(subpath);
1793 }
1794
1795 self.subpaths[cleanPath] = val;
1796 if (val) {
1797 return 'real';
1798 }
1799 if (isNested) {
1800 return 'nested';
1801 }
1802 return 'adhocOrUndefined';
1803}
1804
1805
1806/*!
1807 * ignore
1808 */
1809
1810function getPositionalPath(self, path, cleanPath) {
1811 getPositionalPathType(self, path, cleanPath);
1812 return self.subpaths[cleanPath];
1813}
1814
1815/**
1816 * Adds a method call to the queue.
1817 *
1818 * #### Example:
1819 *
1820 * schema.methods.print = function() { console.log(this); };
1821 * schema.queue('print', []); // Print the doc every one is instantiated
1822 *
1823 * const Model = mongoose.model('Test', schema);
1824 * new Model({ name: 'test' }); // Prints '{"_id": ..., "name": "test" }'
1825 *
1826 * @param {String} name name of the document method to call later
1827 * @param {Array} args arguments to pass to the method
1828 * @api public
1829 */
1830
1831Schema.prototype.queue = function(name, args) {
1832 this.callQueue.push([name, args]);
1833 return this;
1834};
1835
1836/**
1837 * Defines a pre hook for the model.
1838 *
1839 * #### Example:
1840 *
1841 * const toySchema = new Schema({ name: String, created: Date });
1842 *
1843 * toySchema.pre('save', function(next) {
1844 * if (!this.created) this.created = new Date;
1845 * next();
1846 * });
1847 *
1848 * toySchema.pre('validate', function(next) {
1849 * if (this.name !== 'Woody') this.name = 'Woody';
1850 * next();
1851 * });
1852 *
1853 * // Equivalent to calling `pre()` on `find`, `findOne`, `findOneAndUpdate`.
1854 * toySchema.pre(/^find/, function(next) {
1855 * console.log(this.getFilter());
1856 * });
1857 *
1858 * // Equivalent to calling `pre()` on `updateOne`, `findOneAndUpdate`.
1859 * toySchema.pre(['updateOne', 'findOneAndUpdate'], function(next) {
1860 * console.log(this.getFilter());
1861 * });
1862 *
1863 * toySchema.pre('deleteOne', function() {
1864 * // Runs when you call `Toy.deleteOne()`
1865 * });
1866 *
1867 * toySchema.pre('deleteOne', { document: true }, function() {
1868 * // Runs when you call `doc.deleteOne()`
1869 * });
1870 *
1871 * @param {String|RegExp|String[]} methodName The method name or regular expression to match method name
1872 * @param {Object} [options]
1873 * @param {Boolean} [options.document] If `name` is a hook for both document and query middleware, set to `true` to run on document middleware. For example, set `options.document` to `true` to apply this hook to `Document#deleteOne()` rather than `Query#deleteOne()`.
1874 * @param {Boolean} [options.query] If `name` is a hook for both document and query middleware, set to `true` to run on query middleware.
1875 * @param {Function} callback
1876 * @api public
1877 */
1878
1879Schema.prototype.pre = function(name) {
1880 if (name instanceof RegExp) {
1881 const remainingArgs = Array.prototype.slice.call(arguments, 1);
1882 for (const fn of hookNames) {
1883 if (name.test(fn)) {
1884 this.pre.apply(this, [fn].concat(remainingArgs));
1885 }
1886 }
1887 return this;
1888 }
1889 if (Array.isArray(name)) {
1890 const remainingArgs = Array.prototype.slice.call(arguments, 1);
1891 for (const el of name) {
1892 this.pre.apply(this, [el].concat(remainingArgs));
1893 }
1894 return this;
1895 }
1896 this.s.hooks.pre.apply(this.s.hooks, arguments);
1897 return this;
1898};
1899
1900/**
1901 * Defines a post hook for the document
1902 *
1903 * const schema = new Schema(..);
1904 * schema.post('save', function (doc) {
1905 * console.log('this fired after a document was saved');
1906 * });
1907 *
1908 * schema.post('find', function(docs) {
1909 * console.log('this fired after you ran a find query');
1910 * });
1911 *
1912 * schema.post(/Many$/, function(res) {
1913 * console.log('this fired after you ran `updateMany()` or `deleteMany()`');
1914 * });
1915 *
1916 * const Model = mongoose.model('Model', schema);
1917 *
1918 * const m = new Model(..);
1919 * m.save(function(err) {
1920 * console.log('this fires after the `post` hook');
1921 * });
1922 *
1923 * m.find(function(err, docs) {
1924 * console.log('this fires after the post find hook');
1925 * });
1926 *
1927 * @param {String|RegExp|String[]} methodName The method name or regular expression to match method name
1928 * @param {Object} [options]
1929 * @param {Boolean} [options.document] If `name` is a hook for both document and query middleware, set to `true` to run on document middleware.
1930 * @param {Boolean} [options.query] If `name` is a hook for both document and query middleware, set to `true` to run on query middleware.
1931 * @param {Function} fn callback
1932 * @see middleware https://mongoosejs.com/docs/middleware.html
1933 * @see kareem https://npmjs.org/package/kareem
1934 * @api public
1935 */
1936
1937Schema.prototype.post = function(name) {
1938 if (name instanceof RegExp) {
1939 const remainingArgs = Array.prototype.slice.call(arguments, 1);
1940 for (const fn of hookNames) {
1941 if (name.test(fn)) {
1942 this.post.apply(this, [fn].concat(remainingArgs));
1943 }
1944 }
1945 return this;
1946 }
1947 if (Array.isArray(name)) {
1948 const remainingArgs = Array.prototype.slice.call(arguments, 1);
1949 for (const el of name) {
1950 this.post.apply(this, [el].concat(remainingArgs));
1951 }
1952 return this;
1953 }
1954 this.s.hooks.post.apply(this.s.hooks, arguments);
1955 return this;
1956};
1957
1958/**
1959 * Registers a plugin for this schema.
1960 *
1961 * #### Example:
1962 *
1963 * const s = new Schema({ name: String });
1964 * s.plugin(schema => console.log(schema.path('name').path));
1965 * mongoose.model('Test', s); // Prints 'name'
1966 *
1967 * Or with Options:
1968 *
1969 * const s = new Schema({ name: String });
1970 * s.plugin((schema, opts) => console.log(opts.text, schema.path('name').path), { text: "Schema Path Name:" });
1971 * mongoose.model('Test', s); // Prints 'Schema Path Name: name'
1972 *
1973 * @param {Function} plugin The Plugin's callback
1974 * @param {Object} [opts] Options to pass to the plugin
1975 * @param {Boolean} [opts.deduplicate=false] If true, ignore duplicate plugins (same `fn` argument using `===`)
1976 * @see plugins https://mongoosejs.com/docs/plugins.html
1977 * @api public
1978 */
1979
1980Schema.prototype.plugin = function(fn, opts) {
1981 if (typeof fn !== 'function') {
1982 throw new Error('First param to `schema.plugin()` must be a function, ' +
1983 'got "' + (typeof fn) + '"');
1984 }
1985
1986
1987 if (opts && opts.deduplicate) {
1988 for (const plugin of this.plugins) {
1989 if (plugin.fn === fn) {
1990 return this;
1991 }
1992 }
1993 }
1994 this.plugins.push({ fn: fn, opts: opts });
1995
1996 fn(this, opts);
1997 return this;
1998};
1999
2000/**
2001 * Adds an instance method to documents constructed from Models compiled from this schema.
2002 *
2003 * #### Example:
2004 *
2005 * const schema = kittySchema = new Schema(..);
2006 *
2007 * schema.method('meow', function () {
2008 * console.log('meeeeeoooooooooooow');
2009 * })
2010 *
2011 * const Kitty = mongoose.model('Kitty', schema);
2012 *
2013 * const fizz = new Kitty;
2014 * fizz.meow(); // meeeeeooooooooooooow
2015 *
2016 * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as methods.
2017 *
2018 * schema.method({
2019 * purr: function () {}
2020 * , scratch: function () {}
2021 * });
2022 *
2023 * // later
2024 * const fizz = new Kitty;
2025 * fizz.purr();
2026 * fizz.scratch();
2027 *
2028 * NOTE: `Schema.method()` adds instance methods to the `Schema.methods` object. You can also add instance methods directly to the `Schema.methods` object as seen in the [guide](https://mongoosejs.com/docs/guide.html#methods)
2029 *
2030 * @param {String|Object} name The Method Name for a single function, or a Object of "string-function" pairs.
2031 * @param {Function} [fn] The Function in a single-function definition.
2032 * @api public
2033 */
2034
2035Schema.prototype.method = function(name, fn, options) {
2036 if (typeof name !== 'string') {
2037 for (const i in name) {
2038 this.methods[i] = name[i];
2039 this.methodOptions[i] = clone(options);
2040 }
2041 } else {
2042 this.methods[name] = fn;
2043 this.methodOptions[name] = clone(options);
2044 }
2045 return this;
2046};
2047
2048/**
2049 * Adds static "class" methods to Models compiled from this schema.
2050 *
2051 * #### Example:
2052 *
2053 * const schema = new Schema(..);
2054 * // Equivalent to `schema.statics.findByName = function(name) {}`;
2055 * schema.static('findByName', function(name) {
2056 * return this.find({ name: name });
2057 * });
2058 *
2059 * const Drink = mongoose.model('Drink', schema);
2060 * await Drink.findByName('LaCroix');
2061 *
2062 * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as methods.
2063 *
2064 * schema.static({
2065 * findByName: function () {..}
2066 * , findByCost: function () {..}
2067 * });
2068 *
2069 * const Drink = mongoose.model('Drink', schema);
2070 * await Drink.findByName('LaCroix');
2071 * await Drink.findByCost(3);
2072 *
2073 * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as statics.
2074 *
2075 * @param {String|Object} name The Method Name for a single function, or a Object of "string-function" pairs.
2076 * @param {Function} [fn] The Function in a single-function definition.
2077 * @api public
2078 * @see Statics https://mongoosejs.com/docs/guide.html#statics
2079 */
2080
2081Schema.prototype.static = function(name, fn) {
2082 if (typeof name !== 'string') {
2083 for (const i in name) {
2084 this.statics[i] = name[i];
2085 }
2086 } else {
2087 this.statics[name] = fn;
2088 }
2089 return this;
2090};
2091
2092/**
2093 * Defines an index (most likely compound) for this schema.
2094 *
2095 * #### Example:
2096 *
2097 * schema.index({ first: 1, last: -1 })
2098 *
2099 * @param {Object} fields The Fields to index, with the order, available values: `1 | -1 | '2d' | '2dsphere' | 'geoHaystack' | 'hashed' | 'text'`
2100 * @param {Object} [options] Options to pass to [MongoDB driver's `createIndex()` function](https://mongodb.github.io/node-mongodb-native/4.9/classes/Collection.html#createIndex)
2101 * @param {String | number} [options.expires=null] Mongoose-specific syntactic sugar, uses [ms](https://www.npmjs.com/package/ms) to convert `expires` option into seconds for the `expireAfterSeconds` in the above link.
2102 * @param {String} [options.language_override=null] Tells mongodb to use the specified field instead of `language` for parsing text indexes.
2103 * @api public
2104 */
2105
2106Schema.prototype.index = function(fields, options) {
2107 fields || (fields = {});
2108 options || (options = {});
2109
2110 if (options.expires) {
2111 utils.expires(options);
2112 }
2113 for (const key in fields) {
2114 if (this.aliases[key]) {
2115 fields = utils.renameObjKey(fields, key, this.aliases[key]);
2116 }
2117 }
2118 for (const field of Object.keys(fields)) {
2119 if (fields[field] === 'ascending' || fields[field] === 'asc') {
2120 fields[field] = 1;
2121 } else if (fields[field] === 'descending' || fields[field] === 'desc') {
2122 fields[field] = -1;
2123 }
2124 }
2125
2126 this._indexes.push([fields, options]);
2127 return this;
2128};
2129
2130/**
2131 * Sets a schema option.
2132 *
2133 * #### Example:
2134 *
2135 * schema.set('strict'); // 'true' by default
2136 * schema.set('strict', false); // Sets 'strict' to false
2137 * schema.set('strict'); // 'false'
2138 *
2139 * @param {String} key The name of the option to set the value to
2140 * @param {Object} [value] The value to set the option to, if not passed, the option will be reset to default
2141 * @param {Array<string>} [tags] tags to add to read preference if key === 'read'
2142 * @see Schema https://mongoosejs.com/docs/api/schema.html#Schema()
2143 * @api public
2144 */
2145
2146Schema.prototype.set = function(key, value, tags) {
2147 if (arguments.length === 1) {
2148 return this.options[key];
2149 }
2150
2151 switch (key) {
2152 case 'read':
2153 if (typeof value === 'string') {
2154 this.options[key] = { mode: handleReadPreferenceAliases(value), tags };
2155 } else if (Array.isArray(value) && typeof value[0] === 'string') {
2156 this.options[key] = {
2157 mode: handleReadPreferenceAliases(value[0]),
2158 tags: value[1]
2159 };
2160 } else {
2161 this.options[key] = value;
2162 }
2163 this._userProvidedOptions[key] = this.options[key];
2164 break;
2165 case 'timestamps':
2166 this.setupTimestamp(value);
2167 this.options[key] = value;
2168 this._userProvidedOptions[key] = this.options[key];
2169 break;
2170 case '_id':
2171 this.options[key] = value;
2172 this._userProvidedOptions[key] = this.options[key];
2173
2174 if (value && !this.paths['_id']) {
2175 addAutoId(this);
2176 } else if (!value && this.paths['_id'] != null && this.paths['_id'].auto) {
2177 this.remove('_id');
2178 }
2179 break;
2180 default:
2181 this.options[key] = value;
2182 this._userProvidedOptions[key] = this.options[key];
2183 break;
2184 }
2185
2186 // Propagate `strict` and `strictQuery` changes down to implicitly created schemas
2187 if (key === 'strict') {
2188 _propagateOptionsToImplicitlyCreatedSchemas(this, { strict: value });
2189 }
2190 if (key === 'strictQuery') {
2191 _propagateOptionsToImplicitlyCreatedSchemas(this, { strictQuery: value });
2192 }
2193 if (key === 'toObject') {
2194 value = { ...value };
2195 // Avoid propagating transform to implicitly created schemas re: gh-3279
2196 delete value.transform;
2197 _propagateOptionsToImplicitlyCreatedSchemas(this, { toObject: value });
2198 }
2199 if (key === 'toJSON') {
2200 value = { ...value };
2201 // Avoid propagating transform to implicitly created schemas re: gh-3279
2202 delete value.transform;
2203 _propagateOptionsToImplicitlyCreatedSchemas(this, { toJSON: value });
2204 }
2205
2206 return this;
2207};
2208
2209/*!
2210 * Recursively set options on implicitly created schemas
2211 */
2212
2213function _propagateOptionsToImplicitlyCreatedSchemas(baseSchema, options) {
2214 for (const { schema } of baseSchema.childSchemas) {
2215 if (!schema.$implicitlyCreated) {
2216 continue;
2217 }
2218 Object.assign(schema.options, options);
2219 _propagateOptionsToImplicitlyCreatedSchemas(schema, options);
2220 }
2221}
2222
2223/**
2224 * Gets a schema option.
2225 *
2226 * #### Example:
2227 *
2228 * schema.get('strict'); // true
2229 * schema.set('strict', false);
2230 * schema.get('strict'); // false
2231 *
2232 * @param {String} key The name of the Option to get the current value for
2233 * @api public
2234 * @return {Any} the option's value
2235 */
2236
2237Schema.prototype.get = function(key) {
2238 return this.options[key];
2239};
2240
2241const indexTypes = '2d 2dsphere hashed text'.split(' ');
2242
2243/**
2244 * The allowed index types
2245 *
2246 * @property {String[]} indexTypes
2247 * @memberOf Schema
2248 * @static
2249 * @api public
2250 */
2251
2252Object.defineProperty(Schema, 'indexTypes', {
2253 get: function() {
2254 return indexTypes;
2255 },
2256 set: function() {
2257 throw new Error('Cannot overwrite Schema.indexTypes');
2258 }
2259});
2260
2261/**
2262 * Returns a list of indexes that this schema declares, via `schema.index()` or by `index: true` in a path's options.
2263 * Indexes are expressed as an array `[spec, options]`.
2264 *
2265 * #### Example:
2266 *
2267 * const userSchema = new Schema({
2268 * email: { type: String, required: true, unique: true },
2269 * registeredAt: { type: Date, index: true }
2270 * });
2271 *
2272 * // [ [ { email: 1 }, { unique: true, background: true } ],
2273 * // [ { registeredAt: 1 }, { background: true } ] ]
2274 * userSchema.indexes();
2275 *
2276 * [Plugins](https://mongoosejs.com/docs/plugins.html) can use the return value of this function to modify a schema's indexes.
2277 * For example, the below plugin makes every index unique by default.
2278 *
2279 * function myPlugin(schema) {
2280 * for (const index of schema.indexes()) {
2281 * if (index[1].unique === undefined) {
2282 * index[1].unique = true;
2283 * }
2284 * }
2285 * }
2286 *
2287 * @api public
2288 * @return {Array} list of indexes defined in the schema
2289 */
2290
2291Schema.prototype.indexes = function() {
2292 return getIndexes(this);
2293};
2294
2295/**
2296 * Creates a virtual type with the given name.
2297 *
2298 * @param {String} name The name of the Virtual
2299 * @param {Object} [options]
2300 * @param {String|Model} [options.ref] model name or model instance. Marks this as a [populate virtual](https://mongoosejs.com/docs/populate.html#populate-virtuals).
2301 * @param {String|Function} [options.localField] Required for populate virtuals. See [populate virtual docs](https://mongoosejs.com/docs/populate.html#populate-virtuals) for more information.
2302 * @param {String|Function} [options.foreignField] Required for populate virtuals. See [populate virtual docs](https://mongoosejs.com/docs/populate.html#populate-virtuals) for more information.
2303 * @param {Boolean|Function} [options.justOne=false] Only works with populate virtuals. If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), will be a single doc or `null`. Otherwise, the populate virtual will be an array.
2304 * @param {Boolean} [options.count=false] Only works with populate virtuals. If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), this populate virtual will contain the number of documents rather than the documents themselves when you `populate()`.
2305 * @param {Function|null} [options.get=null] Adds a [getter](https://mongoosejs.com/docs/tutorials/getters-setters.html) to this virtual to transform the populated doc.
2306 * @param {Object|Function} [options.match=null] Apply a default [`match` option to populate](https://mongoosejs.com/docs/populate.html#match), adding an additional filter to the populate query.
2307 * @return {VirtualType}
2308 */
2309
2310Schema.prototype.virtual = function(name, options) {
2311 if (name instanceof VirtualType || getConstructorName(name) === 'VirtualType') {
2312 return this.virtual(name.path, name.options);
2313 }
2314 options = new VirtualOptions(options);
2315
2316 if (utils.hasUserDefinedProperty(options, ['ref', 'refPath'])) {
2317 if (options.localField == null) {
2318 throw new Error('Reference virtuals require `localField` option');
2319 }
2320
2321 if (options.foreignField == null) {
2322 throw new Error('Reference virtuals require `foreignField` option');
2323 }
2324
2325 const virtual = this.virtual(name);
2326 virtual.options = options;
2327
2328 this.pre('init', function virtualPreInit(obj, opts) {
2329 if (mpath.has(name, obj)) {
2330 const _v = mpath.get(name, obj);
2331 if (!this.$$populatedVirtuals) {
2332 this.$$populatedVirtuals = {};
2333 }
2334
2335 if (options.justOne || options.count) {
2336 this.$$populatedVirtuals[name] = Array.isArray(_v) ?
2337 _v[0] :
2338 _v;
2339 } else {
2340 this.$$populatedVirtuals[name] = Array.isArray(_v) ?
2341 _v :
2342 _v == null ? [] : [_v];
2343 }
2344
2345 if (opts?.hydratedPopulatedDocs && !options.count) {
2346 const modelNames = virtual._getModelNamesForPopulate(this);
2347 const populatedVal = this.$$populatedVirtuals[name];
2348 if (!Array.isArray(populatedVal) && !populatedVal.$__ && modelNames?.length === 1) {
2349 const PopulateModel = this.db.model(modelNames[0]);
2350 this.$$populatedVirtuals[name] = PopulateModel.hydrate(populatedVal);
2351 } else if (Array.isArray(populatedVal) && modelNames?.length === 1) {
2352 const PopulateModel = this.db.model(modelNames[0]);
2353 for (let i = 0; i < populatedVal.length; ++i) {
2354 if (!populatedVal[i].$__) {
2355 populatedVal[i] = PopulateModel.hydrate(populatedVal[i]);
2356 }
2357 }
2358 }
2359 }
2360
2361 mpath.unset(name, obj);
2362 }
2363 });
2364
2365 virtual.
2366 set(function(v) {
2367 if (!this.$$populatedVirtuals) {
2368 this.$$populatedVirtuals = {};
2369 }
2370
2371 return setPopulatedVirtualValue(
2372 this.$$populatedVirtuals,
2373 name,
2374 v,
2375 options
2376 );
2377 });
2378
2379 if (typeof options.get === 'function') {
2380 virtual.get(options.get);
2381 }
2382
2383 // Workaround for gh-8198: if virtual is under document array, make a fake
2384 // virtual. See gh-8210, gh-13189
2385 const parts = name.split('.');
2386 let cur = parts[0];
2387 for (let i = 0; i < parts.length - 1; ++i) {
2388 if (this.paths[cur] == null) {
2389 continue;
2390 }
2391
2392 if (this.paths[cur].$isMongooseDocumentArray || this.paths[cur].$isSingleNested) {
2393 const remnant = parts.slice(i + 1).join('.');
2394 this.paths[cur].schema.virtual(remnant, options);
2395 break;
2396 }
2397
2398 cur += '.' + parts[i + 1];
2399 }
2400
2401 return virtual;
2402 }
2403
2404 const virtuals = this.virtuals;
2405 const parts = name.split('.');
2406
2407 if (this.pathType(name) === 'real') {
2408 throw new Error('Virtual path "' + name + '"' +
2409 ' conflicts with a real path in the schema');
2410 }
2411
2412 virtuals[name] = parts.reduce(function(mem, part, i) {
2413 mem[part] || (mem[part] = (i === parts.length - 1)
2414 ? new VirtualType(options, name)
2415 : {});
2416 return mem[part];
2417 }, this.tree);
2418
2419 return virtuals[name];
2420};
2421
2422/**
2423 * Returns the virtual type with the given `name`.
2424 *
2425 * @param {String} name The name of the Virtual to get
2426 * @return {VirtualType|null}
2427 */
2428
2429Schema.prototype.virtualpath = function(name) {
2430 return this.virtuals.hasOwnProperty(name) ? this.virtuals[name] : null;
2431};
2432
2433/**
2434 * Removes the given `path` (or [`paths`]).
2435 *
2436 * #### Example:
2437 *
2438 * const schema = new Schema({ name: String, age: Number });
2439 * schema.remove('name');
2440 * schema.path('name'); // Undefined
2441 * schema.path('age'); // SchemaNumber { ... }
2442 *
2443 * Or as a Array:
2444 *
2445 * schema.remove(['name', 'age']);
2446 * schema.path('name'); // Undefined
2447 * schema.path('age'); // Undefined
2448 *
2449 * @param {String|Array} path The Path(s) to remove
2450 * @return {Schema} the Schema instance
2451 * @api public
2452 */
2453Schema.prototype.remove = function(path) {
2454 if (typeof path === 'string') {
2455 path = [path];
2456 }
2457 if (Array.isArray(path)) {
2458 path.forEach(function(name) {
2459 if (this.path(name) == null && !this.nested[name]) {
2460 return;
2461 }
2462 if (this.nested[name]) {
2463 const allKeys = Object.keys(this.paths).
2464 concat(Object.keys(this.nested));
2465 for (const path of allKeys) {
2466 if (path.startsWith(name + '.')) {
2467 delete this.paths[path];
2468 delete this.nested[path];
2469 _deletePath(this, path);
2470 }
2471 }
2472
2473 delete this.nested[name];
2474 _deletePath(this, name);
2475 return;
2476 }
2477
2478 delete this.paths[name];
2479 _deletePath(this, name);
2480 }, this);
2481 }
2482 return this;
2483};
2484
2485/*!
2486 * ignore
2487 */
2488
2489function _deletePath(schema, name) {
2490 const pieces = name.split('.');
2491 const last = pieces.pop();
2492
2493 let branch = schema.tree;
2494
2495 for (const piece of pieces) {
2496 branch = branch[piece];
2497 }
2498
2499 delete branch[last];
2500}
2501
2502/**
2503 * Removes the given virtual or virtuals from the schema.
2504 *
2505 * @param {String|Array} path The virutal path(s) to remove.
2506 * @returns {Schema} the Schema instance, or a mongoose error if the virtual does not exist.
2507 * @api public
2508 */
2509
2510Schema.prototype.removeVirtual = function(path) {
2511 if (typeof path === 'string') {
2512 path = [path];
2513 }
2514 if (Array.isArray(path)) {
2515 for (const virtual of path) {
2516 if (this.virtuals[virtual] == null) {
2517 throw new MongooseError(`Attempting to remove virtual "${virtual}" that does not exist.`);
2518 }
2519 }
2520
2521 for (const virtual of path) {
2522 delete this.paths[virtual];
2523 delete this.virtuals[virtual];
2524 if (virtual.indexOf('.') !== -1) {
2525 mpath.unset(virtual, this.tree);
2526 } else {
2527 delete this.tree[virtual];
2528 }
2529 }
2530 }
2531 return this;
2532};
2533
2534/**
2535 * Loads an ES6 class into a schema. Maps [setters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set) + [getters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get), [static methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static),
2536 * and [instance methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Class_body_and_method_definitions)
2537 * to schema [virtuals](https://mongoosejs.com/docs/guide.html#virtuals),
2538 * [statics](https://mongoosejs.com/docs/guide.html#statics), and
2539 * [methods](https://mongoosejs.com/docs/guide.html#methods).
2540 *
2541 * #### Example:
2542 *
2543 * ```javascript
2544 * const md5 = require('md5');
2545 * const userSchema = new Schema({ email: String });
2546 * class UserClass {
2547 * // `gravatarImage` becomes a virtual
2548 * get gravatarImage() {
2549 * const hash = md5(this.email.toLowerCase());
2550 * return `https://www.gravatar.com/avatar/${hash}`;
2551 * }
2552 *
2553 * // `getProfileUrl()` becomes a document method
2554 * getProfileUrl() {
2555 * return `https://mysite.com/${this.email}`;
2556 * }
2557 *
2558 * // `findByEmail()` becomes a static
2559 * static findByEmail(email) {
2560 * return this.findOne({ email });
2561 * }
2562 * }
2563 *
2564 * // `schema` will now have a `gravatarImage` virtual, a `getProfileUrl()` method,
2565 * // and a `findByEmail()` static
2566 * userSchema.loadClass(UserClass);
2567 * ```
2568 *
2569 * @param {Function} model The Class to load
2570 * @param {Boolean} [virtualsOnly] if truthy, only pulls virtuals from the class, not methods or statics
2571 */
2572Schema.prototype.loadClass = function(model, virtualsOnly) {
2573 // Stop copying when hit certain base classes
2574 if (model === Object.prototype ||
2575 model === Function.prototype ||
2576 model.prototype.hasOwnProperty('$isMongooseModelPrototype') ||
2577 model.prototype.hasOwnProperty('$isMongooseDocumentPrototype')) {
2578 return this;
2579 }
2580
2581 this.loadClass(Object.getPrototypeOf(model), virtualsOnly);
2582
2583 // Add static methods
2584 if (!virtualsOnly) {
2585 Object.getOwnPropertyNames(model).forEach(function(name) {
2586 if (name.match(/^(length|name|prototype|constructor|__proto__)$/)) {
2587 return;
2588 }
2589 const prop = Object.getOwnPropertyDescriptor(model, name);
2590 if (prop.hasOwnProperty('value')) {
2591 this.static(name, prop.value);
2592 }
2593 }, this);
2594 }
2595
2596 // Add methods and virtuals
2597 Object.getOwnPropertyNames(model.prototype).forEach(function(name) {
2598 if (name.match(/^(constructor)$/)) {
2599 return;
2600 }
2601 const method = Object.getOwnPropertyDescriptor(model.prototype, name);
2602 if (!virtualsOnly) {
2603 if (typeof method.value === 'function') {
2604 this.method(name, method.value);
2605 }
2606 }
2607 if (typeof method.get === 'function') {
2608 if (this.virtuals[name]) {
2609 this.virtuals[name].getters = [];
2610 }
2611 this.virtual(name).get(method.get);
2612 }
2613 if (typeof method.set === 'function') {
2614 if (this.virtuals[name]) {
2615 this.virtuals[name].setters = [];
2616 }
2617 this.virtual(name).set(method.set);
2618 }
2619 }, this);
2620
2621 return this;
2622};
2623
2624/*!
2625 * ignore
2626 */
2627
2628Schema.prototype._getSchema = function(path) {
2629 const _this = this;
2630 const pathschema = _this.path(path);
2631 const resultPath = [];
2632
2633 if (pathschema) {
2634 pathschema.$fullPath = path;
2635 return pathschema;
2636 }
2637
2638 function search(parts, schema) {
2639 let p = parts.length + 1;
2640 let foundschema;
2641 let trypath;
2642
2643 while (p--) {
2644 trypath = parts.slice(0, p).join('.');
2645 foundschema = schema.path(trypath);
2646 if (foundschema) {
2647 resultPath.push(trypath);
2648
2649 if (foundschema.caster) {
2650 // array of Mixed?
2651 if (foundschema.caster instanceof MongooseTypes.Mixed) {
2652 foundschema.caster.$fullPath = resultPath.join('.');
2653 return foundschema.caster;
2654 }
2655
2656 // Now that we found the array, we need to check if there
2657 // are remaining document paths to look up for casting.
2658 // Also we need to handle array.$.path since schema.path
2659 // doesn't work for that.
2660 // If there is no foundschema.schema we are dealing with
2661 // a path like array.$
2662 if (p !== parts.length) {
2663 if (p + 1 === parts.length && foundschema.$embeddedSchemaType && (parts[p] === '$' || isArrayFilter(parts[p]))) {
2664 return foundschema.$embeddedSchemaType;
2665 }
2666
2667 if (foundschema.schema) {
2668 let ret;
2669 if (parts[p] === '$' || isArrayFilter(parts[p])) {
2670 if (p + 1 === parts.length) {
2671 // comments.$
2672 return foundschema.$embeddedSchemaType;
2673 }
2674 // comments.$.comments.$.title
2675 ret = search(parts.slice(p + 1), foundschema.schema);
2676 if (ret) {
2677 ret.$parentSchemaDocArray = ret.$parentSchemaDocArray ||
2678 (foundschema.schema.$isSingleNested ? null : foundschema);
2679 }
2680 return ret;
2681 }
2682 // this is the last path of the selector
2683 ret = search(parts.slice(p), foundschema.schema);
2684 if (ret) {
2685 ret.$parentSchemaDocArray = ret.$parentSchemaDocArray ||
2686 (foundschema.schema.$isSingleNested ? null : foundschema);
2687 }
2688 return ret;
2689 }
2690 }
2691 } else if (foundschema.$isSchemaMap) {
2692 if (p >= parts.length) {
2693 return foundschema;
2694 }
2695 // Any path in the map will be an instance of the map's embedded schematype
2696 if (p + 1 >= parts.length) {
2697 return foundschema.$__schemaType;
2698 }
2699
2700 if (foundschema.$__schemaType instanceof MongooseTypes.Mixed) {
2701 return foundschema.$__schemaType;
2702 }
2703 if (foundschema.$__schemaType.schema != null) {
2704 // Map of docs
2705 const ret = search(parts.slice(p + 1), foundschema.$__schemaType.schema);
2706 return ret;
2707 }
2708 }
2709
2710 foundschema.$fullPath = resultPath.join('.');
2711
2712 return foundschema;
2713 }
2714 }
2715 }
2716
2717 // look for arrays
2718 const parts = path.split('.');
2719 for (let i = 0; i < parts.length; ++i) {
2720 if (parts[i] === '$' || isArrayFilter(parts[i])) {
2721 // Re: gh-5628, because `schema.path()` doesn't take $ into account.
2722 parts[i] = '0';
2723 }
2724 if (numberRE.test(parts[i])) {
2725 parts[i] = '$';
2726 }
2727 }
2728 return search(parts, _this);
2729};
2730
2731/*!
2732 * ignore
2733 */
2734
2735Schema.prototype._getPathType = function(path) {
2736 const _this = this;
2737 const pathschema = _this.path(path);
2738
2739 if (pathschema) {
2740 return 'real';
2741 }
2742
2743 function search(parts, schema) {
2744 let p = parts.length + 1,
2745 foundschema,
2746 trypath;
2747
2748 while (p--) {
2749 trypath = parts.slice(0, p).join('.');
2750 foundschema = schema.path(trypath);
2751 if (foundschema) {
2752 if (foundschema.caster) {
2753 // array of Mixed?
2754 if (foundschema.caster instanceof MongooseTypes.Mixed) {
2755 return { schema: foundschema, pathType: 'mixed' };
2756 }
2757
2758 // Now that we found the array, we need to check if there
2759 // are remaining document paths to look up for casting.
2760 // Also we need to handle array.$.path since schema.path
2761 // doesn't work for that.
2762 // If there is no foundschema.schema we are dealing with
2763 // a path like array.$
2764 if (p !== parts.length && foundschema.schema) {
2765 if (parts[p] === '$' || isArrayFilter(parts[p])) {
2766 if (p === parts.length - 1) {
2767 return { schema: foundschema, pathType: 'nested' };
2768 }
2769 // comments.$.comments.$.title
2770 return search(parts.slice(p + 1), foundschema.schema);
2771 }
2772 // this is the last path of the selector
2773 return search(parts.slice(p), foundschema.schema);
2774 }
2775 return {
2776 schema: foundschema,
2777 pathType: foundschema.$isSingleNested ? 'nested' : 'array'
2778 };
2779 }
2780 return { schema: foundschema, pathType: 'real' };
2781 } else if (p === parts.length && schema.nested[trypath]) {
2782 return { schema: schema, pathType: 'nested' };
2783 }
2784 }
2785 return { schema: foundschema || schema, pathType: 'undefined' };
2786 }
2787
2788 // look for arrays
2789 return search(path.split('.'), _this);
2790};
2791
2792/*!
2793 * ignore
2794 */
2795
2796function isArrayFilter(piece) {
2797 return piece.startsWith('$[') && piece.endsWith(']');
2798}
2799
2800/**
2801 * Called by `compile()` _right before_ compiling. Good for making any changes to
2802 * the schema that should respect options set by plugins, like `id`
2803 * @method _preCompile
2804 * @memberOf Schema
2805 * @instance
2806 * @api private
2807 */
2808
2809Schema.prototype._preCompile = function _preCompile() {
2810 this.plugin(idGetter, { deduplicate: true });
2811};
2812
2813/*!
2814 * Module exports.
2815 */
2816
2817module.exports = exports = Schema;
2818
2819// require down here because of reference issues
2820
2821/**
2822 * The various built-in Mongoose Schema Types.
2823 *
2824 * #### Example:
2825 *
2826 * const mongoose = require('mongoose');
2827 * const ObjectId = mongoose.Schema.Types.ObjectId;
2828 *
2829 * #### Types:
2830 *
2831 * - [String](https://mongoosejs.com/docs/schematypes.html#strings)
2832 * - [Number](https://mongoosejs.com/docs/schematypes.html#numbers)
2833 * - [Boolean](https://mongoosejs.com/docs/schematypes.html#booleans) | Bool
2834 * - [Array](https://mongoosejs.com/docs/schematypes.html#arrays)
2835 * - [Buffer](https://mongoosejs.com/docs/schematypes.html#buffers)
2836 * - [Date](https://mongoosejs.com/docs/schematypes.html#dates)
2837 * - [ObjectId](https://mongoosejs.com/docs/schematypes.html#objectids) | Oid
2838 * - [Mixed](https://mongoosejs.com/docs/schematypes.html#mixed)
2839 * - [UUID](https://mongoosejs.com/docs/schematypes.html#uuid)
2840 * - [BigInt](https://mongoosejs.com/docs/schematypes.html#bigint)
2841 *
2842 * Using this exposed access to the `Mixed` SchemaType, we can use them in our schema.
2843 *
2844 * const Mixed = mongoose.Schema.Types.Mixed;
2845 * new mongoose.Schema({ _user: Mixed })
2846 *
2847 * @api public
2848 */
2849
2850Schema.Types = MongooseTypes = require('./schema/index');
2851
2852/*!
2853 * ignore
2854 */
2855
2856exports.ObjectId = MongooseTypes.ObjectId;