UNPKG

63.6 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 applyTimestampsToChildren = require('./helpers/update/applyTimestampsToChildren');
16const applyTimestampsToUpdate = require('./helpers/update/applyTimestampsToUpdate');
17const arrayParentSymbol = require('./helpers/symbols').arrayParentSymbol;
18const get = require('./helpers/get');
19const getIndexes = require('./helpers/schema/getIndexes');
20const handleTimestampOption = require('./helpers/schema/handleTimestampOption');
21const merge = require('./helpers/schema/merge');
22const mpath = require('mpath');
23const readPref = require('./driver').get().ReadPreference;
24const symbols = require('./schema/symbols');
25const util = require('util');
26const utils = require('./utils');
27const validateRef = require('./helpers/populate/validateRef');
28
29let MongooseTypes;
30
31const queryHooks = require('./helpers/query/applyQueryMiddleware').
32 middlewareFunctions;
33const documentHooks = require('./helpers/model/applyHooks').middlewareFunctions;
34const hookNames = queryHooks.concat(documentHooks).
35 reduce((s, hook) => s.add(hook), new Set());
36
37let id = 0;
38
39/**
40 * Schema constructor.
41 *
42 * ####Example:
43 *
44 * var child = new Schema({ name: String });
45 * var schema = new Schema({ name: String, age: Number, children: [child] });
46 * var Tree = mongoose.model('Tree', schema);
47 *
48 * // setting schema options
49 * new Schema({ name: String }, { _id: false, autoIndex: false })
50 *
51 * ####Options:
52 *
53 * - [autoIndex](/docs/guide.html#autoIndex): bool - defaults to null (which means use the connection's autoIndex option)
54 * - [autoCreate](/docs/guide.html#autoCreate): bool - defaults to null (which means use the connection's autoCreate option)
55 * - [bufferCommands](/docs/guide.html#bufferCommands): bool - defaults to true
56 * - [capped](/docs/guide.html#capped): bool - defaults to false
57 * - [collection](/docs/guide.html#collection): string - no default
58 * - [id](/docs/guide.html#id): bool - defaults to true
59 * - [_id](/docs/guide.html#_id): bool - defaults to true
60 * - [minimize](/docs/guide.html#minimize): bool - controls [document#toObject](#document_Document-toObject) behavior when called manually - defaults to true
61 * - [read](/docs/guide.html#read): string
62 * - [writeConcern](/docs/guide.html#writeConcern): object - defaults to null, use to override [the MongoDB server's default write concern settings](https://docs.mongodb.com/manual/reference/write-concern/)
63 * - [shardKey](/docs/guide.html#shardKey): object - defaults to `null`
64 * - [strict](/docs/guide.html#strict): bool - defaults to true
65 * - [strictQuery](/docs/guide.html#strictQuery): bool - defaults to false
66 * - [toJSON](/docs/guide.html#toJSON) - object - no default
67 * - [toObject](/docs/guide.html#toObject) - object - no default
68 * - [typeKey](/docs/guide.html#typeKey) - string - defaults to 'type'
69 * - [typePojoToMixed](/docs/guide.html#typePojoToMixed) - boolean - defaults to true. Determines whether a type set to a POJO becomes a Mixed path or a Subdocument
70 * - [useNestedStrict](/docs/guide.html#useNestedStrict) - boolean - defaults to false
71 * - [validateBeforeSave](/docs/guide.html#validateBeforeSave) - bool - defaults to `true`
72 * - [versionKey](/docs/guide.html#versionKey): string - defaults to "__v"
73 * - [collation](/docs/guide.html#collation): object - defaults to null (which means use no collation)
74 * - [selectPopulatedPaths](/docs/guide.html#selectPopulatedPaths): boolean - defaults to `true`
75 * - [skipVersioning](/docs/guide.html#skipVersioning): object - paths to exclude from versioning
76 * - [timestamps](/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.
77 * - [storeSubdocValidationError](/docs/guide.html#storeSubdocValidationError): boolean - Defaults to true. If false, Mongoose will wrap validation errors in single nested document subpaths into a single validation error on the single nested subdoc's path.
78 *
79 * ####Options for Nested Schemas:
80 * - `excludeIndexes`: bool - defaults to `false`. If `true`, skip building indexes on this schema's paths.
81 *
82 * ####Note:
83 *
84 * _When nesting schemas, (`children` in the example above), always declare the child schema first before passing it into its parent._
85 *
86 * @param {Object|Schema|Array} [definition] Can be one of: object describing schema paths, or schema to copy, or array of objects and schemas
87 * @param {Object} [options]
88 * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter
89 * @event `init`: Emitted after the schema is compiled into a `Model`.
90 * @api public
91 */
92
93function Schema(obj, options) {
94 if (!(this instanceof Schema)) {
95 return new Schema(obj, options);
96 }
97
98 this.obj = obj;
99 this.paths = {};
100 this.aliases = {};
101 this.subpaths = {};
102 this.virtuals = {};
103 this.singleNestedPaths = {};
104 this.nested = {};
105 this.inherits = {};
106 this.callQueue = [];
107 this._indexes = [];
108 this.methods = {};
109 this.methodOptions = {};
110 this.statics = {};
111 this.tree = {};
112 this.query = {};
113 this.childSchemas = [];
114 this.plugins = [];
115 // For internal debugging. Do not use this to try to save a schema in MDB.
116 this.$id = ++id;
117
118 this.s = {
119 hooks: new Kareem()
120 };
121
122 this.options = this.defaultOptions(options);
123
124 // build paths
125 if (Array.isArray(obj)) {
126 for (const definition of obj) {
127 this.add(definition);
128 }
129 } else if (obj) {
130 this.add(obj);
131 }
132
133 // check if _id's value is a subdocument (gh-2276)
134 const _idSubDoc = obj && obj._id && utils.isObject(obj._id);
135
136 // ensure the documents get an auto _id unless disabled
137 const auto_id = !this.paths['_id'] &&
138 (!this.options.noId && this.options._id) && !_idSubDoc;
139
140 if (auto_id) {
141 addAutoId(this);
142 }
143
144 this.setupTimestamp(this.options.timestamps);
145}
146
147/*!
148 * Create virtual properties with alias field
149 */
150function aliasFields(schema, paths) {
151 paths = paths || Object.keys(schema.paths);
152 for (const path of paths) {
153 const options = get(schema.paths[path], 'options');
154 if (options == null) {
155 continue;
156 }
157
158 const prop = schema.paths[path].path;
159 const alias = options.alias;
160
161 if (!alias) {
162 continue;
163 }
164
165 if (typeof alias !== 'string') {
166 throw new Error('Invalid value for alias option on ' + prop + ', got ' + alias);
167 }
168
169 schema.aliases[alias] = prop;
170
171 schema.
172 virtual(alias).
173 get((function(p) {
174 return function() {
175 if (typeof this.get === 'function') {
176 return this.get(p);
177 }
178 return this[p];
179 };
180 })(prop)).
181 set((function(p) {
182 return function(v) {
183 return this.set(p, v);
184 };
185 })(prop));
186 }
187}
188
189/*!
190 * Inherit from EventEmitter.
191 */
192Schema.prototype = Object.create(EventEmitter.prototype);
193Schema.prototype.constructor = Schema;
194Schema.prototype.instanceOfSchema = true;
195
196/*!
197 * ignore
198 */
199
200Object.defineProperty(Schema.prototype, '$schemaType', {
201 configurable: false,
202 enumerable: false,
203 writable: true
204});
205
206/**
207 * Array of child schemas (from document arrays and single nested subdocs)
208 * and their corresponding compiled models. Each element of the array is
209 * an object with 2 properties: `schema` and `model`.
210 *
211 * This property is typically only useful for plugin authors and advanced users.
212 * You do not need to interact with this property at all to use mongoose.
213 *
214 * @api public
215 * @property childSchemas
216 * @memberOf Schema
217 * @instance
218 */
219
220Object.defineProperty(Schema.prototype, 'childSchemas', {
221 configurable: false,
222 enumerable: true,
223 writable: true
224});
225
226/**
227 * The original object passed to the schema constructor
228 *
229 * ####Example:
230 *
231 * var schema = new Schema({ a: String }).add({ b: String });
232 * schema.obj; // { a: String }
233 *
234 * @api public
235 * @property obj
236 * @memberOf Schema
237 * @instance
238 */
239
240Schema.prototype.obj;
241
242/**
243 * The paths defined on this schema. The keys are the top-level paths
244 * in this schema, and the values are instances of the SchemaType class.
245 *
246 * ####Example:
247 * const schema = new Schema({ name: String }, { _id: false });
248 * schema.paths; // { name: SchemaString { ... } }
249 *
250 * schema.add({ age: Number });
251 * schema.paths; // { name: SchemaString { ... }, age: SchemaNumber { ... } }
252 *
253 * @api public
254 * @property paths
255 * @memberOf Schema
256 * @instance
257 */
258
259Schema.prototype.paths;
260
261/**
262 * Schema as a tree
263 *
264 * ####Example:
265 * {
266 * '_id' : ObjectId
267 * , 'nested' : {
268 * 'key' : String
269 * }
270 * }
271 *
272 * @api private
273 * @property tree
274 * @memberOf Schema
275 * @instance
276 */
277
278Schema.prototype.tree;
279
280/**
281 * Returns a deep copy of the schema
282 *
283 * ####Example:
284 *
285 * const schema = new Schema({ name: String });
286 * const clone = schema.clone();
287 * clone === schema; // false
288 * clone.path('name'); // SchemaString { ... }
289 *
290 * @return {Schema} the cloned schema
291 * @api public
292 * @memberOf Schema
293 * @instance
294 */
295
296Schema.prototype.clone = function() {
297 const s = new Schema({}, this._userProvidedOptions);
298 s.base = this.base;
299 s.obj = this.obj;
300 s.options = utils.clone(this.options);
301 s.callQueue = this.callQueue.map(function(f) { return f; });
302 s.methods = utils.clone(this.methods);
303 s.methodOptions = utils.clone(this.methodOptions);
304 s.statics = utils.clone(this.statics);
305 s.query = utils.clone(this.query);
306 s.plugins = Array.prototype.slice.call(this.plugins);
307 s._indexes = utils.clone(this._indexes);
308 s.s.hooks = this.s.hooks.clone();
309
310 s.tree = utils.clone(this.tree);
311 s.paths = utils.clone(this.paths);
312 s.nested = utils.clone(this.nested);
313 s.subpaths = utils.clone(this.subpaths);
314 s.singleNestedPaths = utils.clone(this.singleNestedPaths);
315 s.childSchemas = gatherChildSchemas(s);
316
317 s.virtuals = utils.clone(this.virtuals);
318 s.$globalPluginsApplied = this.$globalPluginsApplied;
319 s.$isRootDiscriminator = this.$isRootDiscriminator;
320 s.$implicitlyCreated = this.$implicitlyCreated;
321
322 if (this.discriminatorMapping != null) {
323 s.discriminatorMapping = Object.assign({}, this.discriminatorMapping);
324 }
325 if (this.discriminators != null) {
326 s.discriminators = Object.assign({}, this.discriminators);
327 }
328
329 s.aliases = Object.assign({}, this.aliases);
330
331 // Bubble up `init` for backwards compat
332 s.on('init', v => this.emit('init', v));
333
334 return s;
335};
336
337/**
338 * Returns a new schema that has the picked `paths` from this schema.
339 *
340 * This method is analagous to [Lodash's `pick()` function](https://lodash.com/docs/4.17.15#pick) for Mongoose schemas.
341 *
342 * ####Example:
343 *
344 * const schema = Schema({ name: String, age: Number });
345 * // Creates a new schema with the same `name` path as `schema`,
346 * // but no `age` path.
347 * const newSchema = schema.pick(['name']);
348 *
349 * newSchema.path('name'); // SchemaString { ... }
350 * newSchema.path('age'); // undefined
351 *
352 * @param {Array} paths list of paths to pick
353 * @param {Object} [options] options to pass to the schema constructor. Defaults to `this.options` if not set.
354 * @return {Schema}
355 * @api public
356 */
357
358Schema.prototype.pick = function(paths, options) {
359 const newSchema = new Schema({}, options || this.options);
360 if (!Array.isArray(paths)) {
361 throw new MongooseError('Schema#pick() only accepts an array argument, ' +
362 'got "' + typeof paths + '"');
363 }
364
365 for (const path of paths) {
366 if (this.nested[path]) {
367 newSchema.add({ [path]: get(this.tree, path) });
368 } else {
369 const schematype = this.path(path);
370 if (schematype == null) {
371 throw new MongooseError('Path `' + path + '` is not in the schema');
372 }
373 newSchema.add({ [path]: schematype });
374 }
375 }
376
377 return newSchema;
378};
379
380/**
381 * Returns default options for this schema, merged with `options`.
382 *
383 * @param {Object} options
384 * @return {Object}
385 * @api private
386 */
387
388Schema.prototype.defaultOptions = function(options) {
389 if (options && options.safe === false) {
390 options.safe = {w: 0};
391 }
392
393 if (options && options.safe && options.safe.w === 0) {
394 // if you turn off safe writes, then versioning goes off as well
395 options.versionKey = false;
396 }
397
398 this._userProvidedOptions = options == null ? {} : utils.clone(options);
399
400 const baseOptions = get(this, 'base.options', {});
401 options = utils.options({
402 strict: 'strict' in baseOptions ? baseOptions.strict : true,
403 bufferCommands: true,
404 capped: false, // { size, max, autoIndexId }
405 versionKey: '__v',
406 discriminatorKey: '__t',
407 minimize: true,
408 autoIndex: null,
409 shardKey: null,
410 read: null,
411 validateBeforeSave: true,
412 // the following are only applied at construction time
413 noId: false, // deprecated, use { _id: false }
414 _id: true,
415 noVirtualId: false, // deprecated, use { id: false }
416 id: true,
417 typeKey: 'type',
418 typePojoToMixed: 'typePojoToMixed' in baseOptions ? baseOptions.typePojoToMixed : true
419 }, utils.clone(options));
420
421 if (options.read) {
422 options.read = readPref(options.read);
423 }
424
425 return options;
426};
427
428/**
429 * Adds key path / schema type pairs to this schema.
430 *
431 * ####Example:
432 *
433 * const ToySchema = new Schema();
434 * ToySchema.add({ name: 'string', color: 'string', price: 'number' });
435 *
436 * const TurboManSchema = new Schema();
437 * // You can also `add()` another schema and copy over all paths, virtuals,
438 * // getters, setters, indexes, methods, and statics.
439 * TurboManSchema.add(ToySchema).add({ year: Number });
440 *
441 * @param {Object|Schema} obj plain object with paths to add, or another schema
442 * @param {String} [prefix] path to prefix the newly added paths with
443 * @return {Schema} the Schema instance
444 * @api public
445 */
446
447Schema.prototype.add = function add(obj, prefix) {
448 if (obj instanceof Schema) {
449 merge(this, obj);
450 return this;
451 }
452
453 // Special case: setting top-level `_id` to false should convert to disabling
454 // the `_id` option. This behavior never worked before 5.4.11 but numerous
455 // codebases use it (see gh-7516, gh-7512).
456 if (obj._id === false && prefix == null) {
457 this.options._id = false;
458 }
459
460 prefix = prefix || '';
461 const keys = Object.keys(obj);
462
463 for (let i = 0; i < keys.length; ++i) {
464 const key = keys[i];
465 const fullPath = prefix + key;
466
467 if (obj[key] == null) {
468 throw new TypeError('Invalid value for schema path `' + fullPath +
469 '`, got value "' + obj[key] + '"');
470 }
471 // Retain `_id: false` but don't set it as a path, re: gh-8274.
472 if (key === '_id' && obj[key] === false) {
473 continue;
474 }
475 if (obj[key] instanceof VirtualType) {
476 this.virtual(obj[key]);
477 continue;
478 }
479
480 if (Array.isArray(obj[key]) && obj[key].length === 1 && obj[key][0] == null) {
481 throw new TypeError('Invalid value for schema Array path `' + fullPath +
482 '`, got value "' + obj[key][0] + '"');
483 }
484
485 if (!(utils.isPOJO(obj[key]) || obj[key] instanceof SchemaTypeOptions)) {
486 // Special-case: Non-options definitely a path so leaf at this node
487 // Examples: Schema instances, SchemaType instances
488 if (prefix) {
489 this.nested[prefix.substr(0, prefix.length - 1)] = true;
490 }
491 this.path(prefix + key, obj[key]);
492 } else if (Object.keys(obj[key]).length < 1) {
493 // Special-case: {} always interpreted as Mixed path so leaf at this node
494 if (prefix) {
495 this.nested[prefix.substr(0, prefix.length - 1)] = true;
496 }
497 this.path(fullPath, obj[key]); // mixed type
498 } else if (!obj[key][this.options.typeKey] || (this.options.typeKey === 'type' && obj[key].type.type)) {
499 // Special-case: POJO with no bona-fide type key - interpret as tree of deep paths so recurse
500 // nested object { last: { name: String }}
501 this.nested[fullPath] = true;
502 this.add(obj[key], fullPath + '.');
503 } else {
504 // There IS a bona-fide type key that may also be a POJO
505 if (!this.options.typePojoToMixed && utils.isPOJO(obj[key][this.options.typeKey])) {
506 // If a POJO is the value of a type key, make it a subdocument
507 if (prefix) {
508 this.nested[prefix.substr(0, prefix.length - 1)] = true;
509 }
510 const schemaWrappedPath = Object.assign({}, obj[key], { type: new Schema(obj[key][this.options.typeKey]) });
511 this.path(prefix + key, schemaWrappedPath);
512 } else {
513 // Either the type is non-POJO or we interpret it as Mixed anyway
514 if (prefix) {
515 this.nested[prefix.substr(0, prefix.length - 1)] = true;
516 }
517 this.path(prefix + key, obj[key]);
518 }
519 }
520 }
521
522 const addedKeys = Object.keys(obj).
523 map(key => prefix ? prefix + key : key);
524 aliasFields(this, addedKeys);
525 return this;
526};
527
528/**
529 * Reserved document keys.
530 *
531 * Keys in this object are names that are rejected in schema declarations
532 * because they conflict with Mongoose functionality. If you create a schema
533 * using `new Schema()` with one of these property names, Mongoose will throw
534 * an error.
535 *
536 * - prototype
537 * - emit
538 * - on
539 * - once
540 * - listeners
541 * - removeListener
542 * - collection
543 * - db
544 * - errors
545 * - init
546 * - isModified
547 * - isNew
548 * - get
549 * - modelName
550 * - save
551 * - schema
552 * - toObject
553 * - validate
554 * - remove
555 * - populated
556 * - _pres
557 * - _posts
558 *
559 * _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.
560 *
561 * var schema = new Schema(..);
562 * schema.methods.init = function () {} // potentially breaking
563 */
564
565Schema.reserved = Object.create(null);
566Schema.prototype.reserved = Schema.reserved;
567const reserved = Schema.reserved;
568// Core object
569reserved['prototype'] =
570// EventEmitter
571reserved.emit =
572reserved.on =
573reserved.once =
574reserved.listeners =
575reserved.removeListener =
576// document properties and functions
577reserved.collection =
578reserved.db =
579reserved.errors =
580reserved.init =
581reserved.isModified =
582reserved.isNew =
583reserved.get =
584reserved.modelName =
585reserved.save =
586reserved.schema =
587reserved.toObject =
588reserved.validate =
589reserved.remove =
590reserved.populated = 1;
591
592/*!
593 * Document keys to print warnings for
594 */
595
596const warnings = {};
597warnings.increment = '`increment` should not be used as a schema path name ' +
598 'unless you have disabled versioning.';
599
600/**
601 * Gets/sets schema paths.
602 *
603 * Sets a path (if arity 2)
604 * Gets a path (if arity 1)
605 *
606 * ####Example
607 *
608 * schema.path('name') // returns a SchemaType
609 * schema.path('name', Number) // changes the schemaType of `name` to Number
610 *
611 * @param {String} path
612 * @param {Object} constructor
613 * @api public
614 */
615
616Schema.prototype.path = function(path, obj) {
617 // Convert to '.$' to check subpaths re: gh-6405
618 const cleanPath = _pathToPositionalSyntax(path);
619 if (obj === undefined) {
620 let schematype = _getPath(this, path, cleanPath);
621 if (schematype != null) {
622 return schematype;
623 }
624
625 // Look for maps
626 const mapPath = getMapPath(this, path);
627 if (mapPath != null) {
628 return mapPath;
629 }
630
631 // Look if a parent of this path is mixed
632 schematype = this.hasMixedParent(cleanPath);
633 if (schematype != null) {
634 return schematype;
635 }
636
637 // subpaths?
638 return /\.\d+\.?.*$/.test(path)
639 ? getPositionalPath(this, path)
640 : undefined;
641 }
642
643 // some path names conflict with document methods
644 if (reserved[path]) {
645 throw new Error('`' + path + '` may not be used as a schema pathname');
646 }
647
648 if (warnings[path]) {
649 console.log('WARN: ' + warnings[path]);
650 }
651
652 if (typeof obj === 'object' && utils.hasUserDefinedProperty(obj, 'ref')) {
653 validateRef(obj.ref, path);
654 }
655
656 // update the tree
657 const subpaths = path.split(/\./);
658 const last = subpaths.pop();
659 let branch = this.tree;
660
661 subpaths.forEach(function(sub, i) {
662 if (!branch[sub]) {
663 branch[sub] = {};
664 }
665 if (typeof branch[sub] !== 'object') {
666 const msg = 'Cannot set nested path `' + path + '`. '
667 + 'Parent path `'
668 + subpaths.slice(0, i).concat([sub]).join('.')
669 + '` already set to type ' + branch[sub].name
670 + '.';
671 throw new Error(msg);
672 }
673 branch = branch[sub];
674 });
675
676 branch[last] = utils.clone(obj);
677
678 this.paths[path] = this.interpretAsType(path, obj, this.options);
679 const schemaType = this.paths[path];
680
681 if (schemaType.$isSchemaMap) {
682 // Maps can have arbitrary keys, so `$*` is internal shorthand for "any key"
683 // The '$' is to imply this path should never be stored in MongoDB so we
684 // can easily build a regexp out of this path, and '*' to imply "any key."
685 const mapPath = path + '.$*';
686 let _mapType = { type: {} };
687 if (utils.hasUserDefinedProperty(obj, 'of')) {
688 const isInlineSchema = utils.isPOJO(obj.of) &&
689 Object.keys(obj.of).length > 0 &&
690 !utils.hasUserDefinedProperty(obj.of, this.options.typeKey);
691 _mapType = isInlineSchema ? new Schema(obj.of) : obj.of;
692 }
693 this.paths[mapPath] = this.interpretAsType(mapPath,
694 _mapType, this.options);
695 schemaType.$__schemaType = this.paths[mapPath];
696 }
697
698 if (schemaType.$isSingleNested) {
699 for (const key in schemaType.schema.paths) {
700 this.singleNestedPaths[path + '.' + key] = schemaType.schema.paths[key];
701 }
702 for (const key in schemaType.schema.singleNestedPaths) {
703 this.singleNestedPaths[path + '.' + key] =
704 schemaType.schema.singleNestedPaths[key];
705 }
706 for (const key in schemaType.schema.subpaths) {
707 this.singleNestedPaths[path + '.' + key] =
708 schemaType.schema.subpaths[key];
709 }
710
711 Object.defineProperty(schemaType.schema, 'base', {
712 configurable: true,
713 enumerable: false,
714 writable: false,
715 value: this.base
716 });
717
718 schemaType.caster.base = this.base;
719 this.childSchemas.push({
720 schema: schemaType.schema,
721 model: schemaType.caster
722 });
723 } else if (schemaType.$isMongooseDocumentArray) {
724 Object.defineProperty(schemaType.schema, 'base', {
725 configurable: true,
726 enumerable: false,
727 writable: false,
728 value: this.base
729 });
730
731 schemaType.casterConstructor.base = this.base;
732 this.childSchemas.push({
733 schema: schemaType.schema,
734 model: schemaType.casterConstructor
735 });
736 }
737
738 if (schemaType.$isMongooseArray && schemaType.caster instanceof SchemaType) {
739 let arrayPath = path;
740 let _schemaType = schemaType;
741
742 const toAdd = [];
743 while (_schemaType.$isMongooseArray) {
744 arrayPath = arrayPath + '.$';
745
746 // Skip arrays of document arrays
747 if (_schemaType.$isMongooseDocumentArray) {
748 _schemaType = _schemaType.$embeddedSchemaType.clone();
749 } else {
750 _schemaType = _schemaType.caster.clone();
751 }
752
753 _schemaType.path = arrayPath;
754 toAdd.push(_schemaType);
755 }
756
757 for (const _schemaType of toAdd) {
758 this.subpaths[_schemaType.path] = _schemaType;
759 }
760 }
761
762 if (schemaType.$isMongooseDocumentArray) {
763 for (const key of Object.keys(schemaType.schema.paths)) {
764 this.subpaths[path + '.' + key] = schemaType.schema.paths[key];
765 schemaType.schema.paths[key].$isUnderneathDocArray = true;
766 }
767 for (const key of Object.keys(schemaType.schema.subpaths)) {
768 this.subpaths[path + '.' + key] = schemaType.schema.subpaths[key];
769 schemaType.schema.subpaths[key].$isUnderneathDocArray = true;
770 }
771 for (const key of Object.keys(schemaType.schema.singleNestedPaths)) {
772 this.subpaths[path + '.' + key] = schemaType.schema.singleNestedPaths[key];
773 schemaType.schema.singleNestedPaths[key].$isUnderneathDocArray = true;
774 }
775 }
776
777 return this;
778};
779
780/*!
781 * ignore
782 */
783
784function gatherChildSchemas(schema) {
785 const childSchemas = [];
786
787 for (const path of Object.keys(schema.paths)) {
788 const schematype = schema.paths[path];
789 if (schematype.$isMongooseDocumentArray || schematype.$isSingleNested) {
790 childSchemas.push({ schema: schematype.schema, model: schematype.caster });
791 }
792 }
793
794 return childSchemas;
795}
796
797/*!
798 * ignore
799 */
800
801function _getPath(schema, path, cleanPath) {
802 if (schema.paths.hasOwnProperty(path)) {
803 return schema.paths[path];
804 }
805 if (schema.subpaths.hasOwnProperty(cleanPath)) {
806 return schema.subpaths[cleanPath];
807 }
808 if (schema.singleNestedPaths.hasOwnProperty(cleanPath)) {
809 return schema.singleNestedPaths[cleanPath];
810 }
811
812 return null;
813}
814
815/*!
816 * ignore
817 */
818
819function _pathToPositionalSyntax(path) {
820 if (!/\.\d+/.test(path)) {
821 return path;
822 }
823 return path.replace(/\.\d+\./g, '.$.').replace(/\.\d+$/, '.$');
824}
825
826/*!
827 * ignore
828 */
829
830function getMapPath(schema, path) {
831 for (const _path of Object.keys(schema.paths)) {
832 if (!_path.includes('.$*')) {
833 continue;
834 }
835 const re = new RegExp('^' + _path.replace(/\.\$\*/g, '\\.[^.]+') + '$');
836 if (re.test(path)) {
837 return schema.paths[_path];
838 }
839 }
840
841 return null;
842}
843
844/**
845 * The Mongoose instance this schema is associated with
846 *
847 * @property base
848 * @api private
849 */
850
851Object.defineProperty(Schema.prototype, 'base', {
852 configurable: true,
853 enumerable: false,
854 writable: true,
855 value: null
856});
857
858/**
859 * Converts type arguments into Mongoose Types.
860 *
861 * @param {String} path
862 * @param {Object} obj constructor
863 * @api private
864 */
865
866Schema.prototype.interpretAsType = function(path, obj, options) {
867 if (obj instanceof SchemaType) {
868 return obj;
869 }
870
871 // If this schema has an associated Mongoose object, use the Mongoose object's
872 // copy of SchemaTypes re: gh-7158 gh-6933
873 const MongooseTypes = this.base != null ? this.base.Schema.Types : Schema.Types;
874
875 if (!utils.isPOJO(obj) && !(obj instanceof SchemaTypeOptions)) {
876 const constructorName = utils.getFunctionName(obj.constructor);
877 if (constructorName !== 'Object') {
878 const oldObj = obj;
879 obj = {};
880 obj[options.typeKey] = oldObj;
881 }
882 }
883
884 // Get the type making sure to allow keys named "type"
885 // and default to mixed if not specified.
886 // { type: { type: String, default: 'freshcut' } }
887 let type = obj[options.typeKey] && (options.typeKey !== 'type' || !obj.type.type)
888 ? obj[options.typeKey]
889 : {};
890 let name;
891
892 if (utils.isPOJO(type) || type === 'mixed') {
893 return new MongooseTypes.Mixed(path, obj);
894 }
895
896 if (Array.isArray(type) || Array === type || type === 'array') {
897 // if it was specified through { type } look for `cast`
898 let cast = (Array === type || type === 'array')
899 ? obj.cast
900 : type[0];
901
902 if (cast && cast.instanceOfSchema) {
903 return new MongooseTypes.DocumentArray(path, cast, obj);
904 }
905 if (cast &&
906 cast[options.typeKey] &&
907 cast[options.typeKey].instanceOfSchema) {
908 return new MongooseTypes.DocumentArray(path, cast[options.typeKey], obj, cast);
909 }
910
911 if (Array.isArray(cast)) {
912 return new MongooseTypes.Array(path, this.interpretAsType(path, cast, options), obj);
913 }
914
915 if (typeof cast === 'string') {
916 cast = MongooseTypes[cast.charAt(0).toUpperCase() + cast.substring(1)];
917 } else if (cast && (!cast[options.typeKey] || (options.typeKey === 'type' && cast.type.type))
918 && utils.isPOJO(cast)) {
919 if (Object.keys(cast).length) {
920 // The `minimize` and `typeKey` options propagate to child schemas
921 // declared inline, like `{ arr: [{ val: { $type: String } }] }`.
922 // See gh-3560
923 const childSchemaOptions = {minimize: options.minimize};
924 if (options.typeKey) {
925 childSchemaOptions.typeKey = options.typeKey;
926 }
927 //propagate 'strict' option to child schema
928 if (options.hasOwnProperty('strict')) {
929 childSchemaOptions.strict = options.strict;
930 }
931 const childSchema = new Schema(cast, childSchemaOptions);
932 childSchema.$implicitlyCreated = true;
933 return new MongooseTypes.DocumentArray(path, childSchema, obj);
934 } else {
935 // Special case: empty object becomes mixed
936 return new MongooseTypes.Array(path, MongooseTypes.Mixed, obj);
937 }
938 }
939
940 if (cast) {
941 type = cast[options.typeKey] && (options.typeKey !== 'type' || !cast.type.type)
942 ? cast[options.typeKey]
943 : cast;
944
945 name = typeof type === 'string'
946 ? type
947 : type.schemaName || utils.getFunctionName(type);
948
949 if (!MongooseTypes.hasOwnProperty(name)) {
950 throw new TypeError('Invalid schema configuration: ' +
951 `\`${name}\` is not a valid type within the array \`${path}\`.` +
952 'See http://bit.ly/mongoose-schematypes for a list of valid schema types.');
953 }
954 }
955
956 return new MongooseTypes.Array(path, cast || MongooseTypes.Mixed, obj, options);
957 }
958
959 if (type && type.instanceOfSchema) {
960 return new MongooseTypes.Embedded(type, path, obj);
961 }
962
963 if (Buffer.isBuffer(type)) {
964 name = 'Buffer';
965 } else if (typeof type === 'function' || typeof type === 'object') {
966 name = type.schemaName || utils.getFunctionName(type);
967 } else {
968 name = type == null ? '' + type : type.toString();
969 }
970
971 if (name) {
972 name = name.charAt(0).toUpperCase() + name.substring(1);
973 }
974 // Special case re: gh-7049 because the bson `ObjectID` class' capitalization
975 // doesn't line up with Mongoose's.
976 if (name === 'ObjectID') {
977 name = 'ObjectId';
978 }
979
980 if (MongooseTypes[name] == null) {
981 throw new TypeError(`Invalid schema configuration: \`${name}\` is not ` +
982 `a valid type at path \`${path}\`. See ` +
983 'http://bit.ly/mongoose-schematypes for a list of valid schema types.');
984 }
985
986 return new MongooseTypes[name](path, obj);
987};
988
989/**
990 * Iterates the schemas paths similar to Array#forEach.
991 *
992 * The callback is passed the pathname and the schemaType instance.
993 *
994 * ####Example:
995 *
996 * const userSchema = new Schema({ name: String, registeredAt: Date });
997 * userSchema.eachPath((pathname, schematype) => {
998 * // Prints twice:
999 * // name SchemaString { ... }
1000 * // registeredAt SchemaDate { ... }
1001 * console.log(pathname, schematype);
1002 * });
1003 *
1004 * @param {Function} fn callback function
1005 * @return {Schema} this
1006 * @api public
1007 */
1008
1009Schema.prototype.eachPath = function(fn) {
1010 const keys = Object.keys(this.paths);
1011 const len = keys.length;
1012
1013 for (let i = 0; i < len; ++i) {
1014 fn(keys[i], this.paths[keys[i]]);
1015 }
1016
1017 return this;
1018};
1019
1020/**
1021 * Returns an Array of path strings that are required by this schema.
1022 *
1023 * ####Example:
1024 * const s = new Schema({
1025 * name: { type: String, required: true },
1026 * age: { type: String, required: true },
1027 * notes: String
1028 * });
1029 * s.requiredPaths(); // [ 'age', 'name' ]
1030 *
1031 * @api public
1032 * @param {Boolean} invalidate refresh the cache
1033 * @return {Array}
1034 */
1035
1036Schema.prototype.requiredPaths = function requiredPaths(invalidate) {
1037 if (this._requiredpaths && !invalidate) {
1038 return this._requiredpaths;
1039 }
1040
1041 const paths = Object.keys(this.paths);
1042 let i = paths.length;
1043 const ret = [];
1044
1045 while (i--) {
1046 const path = paths[i];
1047 if (this.paths[path].isRequired) {
1048 ret.push(path);
1049 }
1050 }
1051 this._requiredpaths = ret;
1052 return this._requiredpaths;
1053};
1054
1055/**
1056 * Returns indexes from fields and schema-level indexes (cached).
1057 *
1058 * @api private
1059 * @return {Array}
1060 */
1061
1062Schema.prototype.indexedPaths = function indexedPaths() {
1063 if (this._indexedpaths) {
1064 return this._indexedpaths;
1065 }
1066 this._indexedpaths = this.indexes();
1067 return this._indexedpaths;
1068};
1069
1070/**
1071 * Returns the pathType of `path` for this schema.
1072 *
1073 * Given a path, returns whether it is a real, virtual, nested, or ad-hoc/undefined path.
1074 *
1075 * ####Example:
1076 * const s = new Schema({ name: String, nested: { foo: String } });
1077 * s.virtual('foo').get(() => 42);
1078 * s.pathType('name'); // "real"
1079 * s.pathType('nested'); // "nested"
1080 * s.pathType('foo'); // "virtual"
1081 * s.pathType('fail'); // "adhocOrUndefined"
1082 *
1083 * @param {String} path
1084 * @return {String}
1085 * @api public
1086 */
1087
1088Schema.prototype.pathType = function(path) {
1089 // Convert to '.$' to check subpaths re: gh-6405
1090 const cleanPath = _pathToPositionalSyntax(path);
1091
1092 if (this.paths.hasOwnProperty(path)) {
1093 return 'real';
1094 }
1095 if (this.virtuals.hasOwnProperty(path)) {
1096 return 'virtual';
1097 }
1098 if (this.nested.hasOwnProperty(path)) {
1099 return 'nested';
1100 }
1101 if (this.subpaths.hasOwnProperty(cleanPath) || this.subpaths.hasOwnProperty(path)) {
1102 return 'real';
1103 }
1104 if (this.singleNestedPaths.hasOwnProperty(cleanPath) || this.singleNestedPaths.hasOwnProperty(path)) {
1105 return 'real';
1106 }
1107
1108 // Look for maps
1109 const mapPath = getMapPath(this, path);
1110 if (mapPath != null) {
1111 return 'real';
1112 }
1113
1114 if (/\.\d+\.|\.\d+$/.test(path)) {
1115 return getPositionalPathType(this, path);
1116 }
1117 return 'adhocOrUndefined';
1118};
1119
1120/**
1121 * Returns true iff this path is a child of a mixed schema.
1122 *
1123 * @param {String} path
1124 * @return {Boolean}
1125 * @api private
1126 */
1127
1128Schema.prototype.hasMixedParent = function(path) {
1129 const subpaths = path.split(/\./g);
1130 path = '';
1131 for (let i = 0; i < subpaths.length; ++i) {
1132 path = i > 0 ? path + '.' + subpaths[i] : subpaths[i];
1133 if (path in this.paths &&
1134 this.paths[path] instanceof MongooseTypes.Mixed) {
1135 return this.paths[path];
1136 }
1137 }
1138
1139 return null;
1140};
1141
1142/**
1143 * Setup updatedAt and createdAt timestamps to documents if enabled
1144 *
1145 * @param {Boolean|Object} timestamps timestamps options
1146 * @api private
1147 */
1148Schema.prototype.setupTimestamp = function(timestamps) {
1149 const childHasTimestamp = this.childSchemas.find(withTimestamp);
1150
1151 function withTimestamp(s) {
1152 const ts = s.schema.options.timestamps;
1153 return !!ts;
1154 }
1155
1156 if (!timestamps && !childHasTimestamp) {
1157 return;
1158 }
1159
1160 const createdAt = handleTimestampOption(timestamps, 'createdAt');
1161 const updatedAt = handleTimestampOption(timestamps, 'updatedAt');
1162 const currentTime = timestamps != null && timestamps.hasOwnProperty('currentTime') ?
1163 timestamps.currentTime :
1164 null;
1165 const schemaAdditions = {};
1166
1167 this.$timestamps = { createdAt: createdAt, updatedAt: updatedAt };
1168
1169 if (updatedAt && !this.paths[updatedAt]) {
1170 schemaAdditions[updatedAt] = Date;
1171 }
1172
1173 if (createdAt && !this.paths[createdAt]) {
1174 schemaAdditions[createdAt] = Date;
1175 }
1176
1177 this.add(schemaAdditions);
1178
1179 this.pre('save', function(next) {
1180 const timestampOption = get(this, '$__.saveOptions.timestamps');
1181 if (timestampOption === false) {
1182 return next();
1183 }
1184
1185 const skipUpdatedAt = timestampOption != null && timestampOption.updatedAt === false;
1186 const skipCreatedAt = timestampOption != null && timestampOption.createdAt === false;
1187
1188 const defaultTimestamp = currentTime != null ?
1189 currentTime() :
1190 (this.ownerDocument ? this.ownerDocument() : this).constructor.base.now();
1191 const auto_id = this._id && this._id.auto;
1192
1193 if (!skipCreatedAt && createdAt && !this.get(createdAt) && this.isSelected(createdAt)) {
1194 this.set(createdAt, auto_id ? this._id.getTimestamp() : defaultTimestamp);
1195 }
1196
1197 if (!skipUpdatedAt && updatedAt && (this.isNew || this.isModified())) {
1198 let ts = defaultTimestamp;
1199 if (this.isNew) {
1200 if (createdAt != null) {
1201 ts = this.$__getValue(createdAt);
1202 } else if (auto_id) {
1203 ts = this._id.getTimestamp();
1204 }
1205 }
1206 this.set(updatedAt, ts);
1207 }
1208
1209 next();
1210 });
1211
1212 this.methods.initializeTimestamps = function() {
1213 const ts = currentTime != null ?
1214 currentTime() :
1215 this.constructor.base.now();
1216 if (createdAt && !this.get(createdAt)) {
1217 this.set(createdAt, ts);
1218 }
1219 if (updatedAt && !this.get(updatedAt)) {
1220 this.set(updatedAt, ts);
1221 }
1222 return this;
1223 };
1224
1225 _setTimestampsOnUpdate[symbols.builtInMiddleware] = true;
1226
1227 const opts = { query: true, model: false };
1228 this.pre('findOneAndUpdate', opts, _setTimestampsOnUpdate);
1229 this.pre('replaceOne', opts, _setTimestampsOnUpdate);
1230 this.pre('update', opts, _setTimestampsOnUpdate);
1231 this.pre('updateOne', opts, _setTimestampsOnUpdate);
1232 this.pre('updateMany', opts, _setTimestampsOnUpdate);
1233
1234 function _setTimestampsOnUpdate(next) {
1235 const now = currentTime != null ?
1236 currentTime() :
1237 this.model.base.now();
1238 applyTimestampsToUpdate(now, createdAt, updatedAt, this.getUpdate(),
1239 this.options, this.schema);
1240 applyTimestampsToChildren(now, this.getUpdate(), this.model.schema);
1241 next();
1242 }
1243};
1244
1245/*!
1246 * ignore. Deprecated re: #6405
1247 */
1248
1249function getPositionalPathType(self, path) {
1250 const subpaths = path.split(/\.(\d+)\.|\.(\d+)$/).filter(Boolean);
1251 if (subpaths.length < 2) {
1252 return self.paths.hasOwnProperty(subpaths[0]) ?
1253 self.paths[subpaths[0]] :
1254 'adhocOrUndefined';
1255 }
1256
1257 let val = self.path(subpaths[0]);
1258 let isNested = false;
1259 if (!val) {
1260 return 'adhocOrUndefined';
1261 }
1262
1263 const last = subpaths.length - 1;
1264
1265 for (let i = 1; i < subpaths.length; ++i) {
1266 isNested = false;
1267 const subpath = subpaths[i];
1268
1269 if (i === last && val && !/\D/.test(subpath)) {
1270 if (val.$isMongooseDocumentArray) {
1271 val = val.$embeddedSchemaType;
1272 } else if (val instanceof MongooseTypes.Array) {
1273 // StringSchema, NumberSchema, etc
1274 val = val.caster;
1275 } else {
1276 val = undefined;
1277 }
1278 break;
1279 }
1280
1281 // ignore if its just a position segment: path.0.subpath
1282 if (!/\D/.test(subpath)) {
1283 // Nested array
1284 if (val instanceof MongooseTypes.Array && i !== last) {
1285 val = val.caster;
1286 }
1287 continue;
1288 }
1289
1290 if (!(val && val.schema)) {
1291 val = undefined;
1292 break;
1293 }
1294
1295 const type = val.schema.pathType(subpath);
1296 isNested = (type === 'nested');
1297 val = val.schema.path(subpath);
1298 }
1299
1300 self.subpaths[path] = val;
1301 if (val) {
1302 return 'real';
1303 }
1304 if (isNested) {
1305 return 'nested';
1306 }
1307 return 'adhocOrUndefined';
1308}
1309
1310
1311/*!
1312 * ignore
1313 */
1314
1315function getPositionalPath(self, path) {
1316 getPositionalPathType(self, path);
1317 return self.subpaths[path];
1318}
1319
1320/**
1321 * Adds a method call to the queue.
1322 *
1323 * ####Example:
1324 *
1325 * schema.methods.print = function() { console.log(this); };
1326 * schema.queue('print', []); // Print the doc every one is instantiated
1327 *
1328 * const Model = mongoose.model('Test', schema);
1329 * new Model({ name: 'test' }); // Prints '{"_id": ..., "name": "test" }'
1330 *
1331 * @param {String} name name of the document method to call later
1332 * @param {Array} args arguments to pass to the method
1333 * @api public
1334 */
1335
1336Schema.prototype.queue = function(name, args) {
1337 this.callQueue.push([name, args]);
1338 return this;
1339};
1340
1341/**
1342 * Defines a pre hook for the document.
1343 *
1344 * ####Example
1345 *
1346 * var toySchema = new Schema({ name: String, created: Date });
1347 *
1348 * toySchema.pre('save', function(next) {
1349 * if (!this.created) this.created = new Date;
1350 * next();
1351 * });
1352 *
1353 * toySchema.pre('validate', function(next) {
1354 * if (this.name !== 'Woody') this.name = 'Woody';
1355 * next();
1356 * });
1357 *
1358 * // Equivalent to calling `pre()` on `find`, `findOne`, `findOneAndUpdate`.
1359 * toySchema.pre(/^find/, function(next) {
1360 * console.log(this.getFilter());
1361 * });
1362 *
1363 * // Equivalent to calling `pre()` on `updateOne`, `findOneAndUpdate`.
1364 * toySchema.pre(['updateOne', 'findOneAndUpdate'], function(next) {
1365 * console.log(this.getFilter());
1366 * });
1367 *
1368 * toySchema.pre('deleteOne', function() {
1369 * // Runs when you call `Toy.deleteOne()`
1370 * });
1371 *
1372 * toySchema.pre('deleteOne', { document: true }, function() {
1373 * // Runs when you call `doc.deleteOne()`
1374 * });
1375 *
1376 * @param {String|RegExp} The method name or regular expression to match method name
1377 * @param {Object} [options]
1378 * @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()`.
1379 * @param {Boolean} [options.query] If `name` is a hook for both document and query middleware, set to `true` to run on query middleware.
1380 * @param {Function} callback
1381 * @api public
1382 */
1383
1384Schema.prototype.pre = function(name) {
1385 if (name instanceof RegExp) {
1386 const remainingArgs = Array.prototype.slice.call(arguments, 1);
1387 for (const fn of hookNames) {
1388 if (name.test(fn)) {
1389 this.pre.apply(this, [fn].concat(remainingArgs));
1390 }
1391 }
1392 return this;
1393 }
1394 if (Array.isArray(name)) {
1395 const remainingArgs = Array.prototype.slice.call(arguments, 1);
1396 for (const el of name) {
1397 this.pre.apply(this, [el].concat(remainingArgs));
1398 }
1399 return this;
1400 }
1401 this.s.hooks.pre.apply(this.s.hooks, arguments);
1402 return this;
1403};
1404
1405/**
1406 * Defines a post hook for the document
1407 *
1408 * var schema = new Schema(..);
1409 * schema.post('save', function (doc) {
1410 * console.log('this fired after a document was saved');
1411 * });
1412 *
1413 * schema.post('find', function(docs) {
1414 * console.log('this fired after you ran a find query');
1415 * });
1416 *
1417 * schema.post(/Many$/, function(res) {
1418 * console.log('this fired after you ran `updateMany()` or `deleteMany()`);
1419 * });
1420 *
1421 * var Model = mongoose.model('Model', schema);
1422 *
1423 * var m = new Model(..);
1424 * m.save(function(err) {
1425 * console.log('this fires after the `post` hook');
1426 * });
1427 *
1428 * m.find(function(err, docs) {
1429 * console.log('this fires after the post find hook');
1430 * });
1431 *
1432 * @param {String|RegExp} The method name or regular expression to match method name
1433 * @param {Object} [options]
1434 * @param {Boolean} [options.document] If `name` is a hook for both document and query middleware, set to `true` to run on document middleware.
1435 * @param {Boolean} [options.query] If `name` is a hook for both document and query middleware, set to `true` to run on query middleware.
1436 * @param {Function} fn callback
1437 * @see middleware http://mongoosejs.com/docs/middleware.html
1438 * @see kareem http://npmjs.org/package/kareem
1439 * @api public
1440 */
1441
1442Schema.prototype.post = function(name) {
1443 if (name instanceof RegExp) {
1444 const remainingArgs = Array.prototype.slice.call(arguments, 1);
1445 for (const fn of hookNames) {
1446 if (name.test(fn)) {
1447 this.post.apply(this, [fn].concat(remainingArgs));
1448 }
1449 }
1450 return this;
1451 }
1452 if (Array.isArray(name)) {
1453 const remainingArgs = Array.prototype.slice.call(arguments, 1);
1454 for (const el of name) {
1455 this.post.apply(this, [el].concat(remainingArgs));
1456 }
1457 return this;
1458 }
1459 this.s.hooks.post.apply(this.s.hooks, arguments);
1460 return this;
1461};
1462
1463/**
1464 * Registers a plugin for this schema.
1465 *
1466 * ####Example:
1467 *
1468 * const s = new Schema({ name: String });
1469 * s.plugin(schema => console.log(schema.path('name').path));
1470 * mongoose.model('Test', s); // Prints 'name'
1471 *
1472 * @param {Function} plugin callback
1473 * @param {Object} [opts]
1474 * @see plugins
1475 * @api public
1476 */
1477
1478Schema.prototype.plugin = function(fn, opts) {
1479 if (typeof fn !== 'function') {
1480 throw new Error('First param to `schema.plugin()` must be a function, ' +
1481 'got "' + (typeof fn) + '"');
1482 }
1483
1484 if (opts &&
1485 opts.deduplicate) {
1486 for (let i = 0; i < this.plugins.length; ++i) {
1487 if (this.plugins[i].fn === fn) {
1488 return this;
1489 }
1490 }
1491 }
1492 this.plugins.push({ fn: fn, opts: opts });
1493
1494 fn(this, opts);
1495 return this;
1496};
1497
1498/**
1499 * Adds an instance method to documents constructed from Models compiled from this schema.
1500 *
1501 * ####Example
1502 *
1503 * var schema = kittySchema = new Schema(..);
1504 *
1505 * schema.method('meow', function () {
1506 * console.log('meeeeeoooooooooooow');
1507 * })
1508 *
1509 * var Kitty = mongoose.model('Kitty', schema);
1510 *
1511 * var fizz = new Kitty;
1512 * fizz.meow(); // meeeeeooooooooooooow
1513 *
1514 * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as methods.
1515 *
1516 * schema.method({
1517 * purr: function () {}
1518 * , scratch: function () {}
1519 * });
1520 *
1521 * // later
1522 * fizz.purr();
1523 * fizz.scratch();
1524 *
1525 * 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](./guide.html#methods)
1526 *
1527 * @param {String|Object} method name
1528 * @param {Function} [fn]
1529 * @api public
1530 */
1531
1532Schema.prototype.method = function(name, fn, options) {
1533 if (typeof name !== 'string') {
1534 for (const i in name) {
1535 this.methods[i] = name[i];
1536 this.methodOptions[i] = utils.clone(options);
1537 }
1538 } else {
1539 this.methods[name] = fn;
1540 this.methodOptions[name] = utils.clone(options);
1541 }
1542 return this;
1543};
1544
1545/**
1546 * Adds static "class" methods to Models compiled from this schema.
1547 *
1548 * ####Example
1549 *
1550 * const schema = new Schema(..);
1551 * // Equivalent to `schema.statics.findByName = function(name) {}`;
1552 * schema.static('findByName', function(name) {
1553 * return this.find({ name: name });
1554 * });
1555 *
1556 * const Drink = mongoose.model('Drink', schema);
1557 * await Drink.findByName('LaCroix');
1558 *
1559 * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as statics.
1560 *
1561 * @param {String|Object} name
1562 * @param {Function} [fn]
1563 * @api public
1564 * @see Statics /docs/guide.html#statics
1565 */
1566
1567Schema.prototype.static = function(name, fn) {
1568 if (typeof name !== 'string') {
1569 for (const i in name) {
1570 this.statics[i] = name[i];
1571 }
1572 } else {
1573 this.statics[name] = fn;
1574 }
1575 return this;
1576};
1577
1578/**
1579 * Defines an index (most likely compound) for this schema.
1580 *
1581 * ####Example
1582 *
1583 * schema.index({ first: 1, last: -1 })
1584 *
1585 * @param {Object} fields
1586 * @param {Object} [options] Options to pass to [MongoDB driver's `createIndex()` function](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#createIndex)
1587 * @param {String} [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.
1588 * @api public
1589 */
1590
1591Schema.prototype.index = function(fields, options) {
1592 fields || (fields = {});
1593 options || (options = {});
1594
1595 if (options.expires) {
1596 utils.expires(options);
1597 }
1598
1599 this._indexes.push([fields, options]);
1600 return this;
1601};
1602
1603/**
1604 * Sets/gets a schema option.
1605 *
1606 * ####Example
1607 *
1608 * schema.set('strict'); // 'true' by default
1609 * schema.set('strict', false); // Sets 'strict' to false
1610 * schema.set('strict'); // 'false'
1611 *
1612 * @param {String} key option name
1613 * @param {Object} [value] if not passed, the current option value is returned
1614 * @see Schema ./
1615 * @api public
1616 */
1617
1618Schema.prototype.set = function(key, value, _tags) {
1619 if (arguments.length === 1) {
1620 return this.options[key];
1621 }
1622
1623 switch (key) {
1624 case 'read':
1625 this.options[key] = readPref(value, _tags);
1626 this._userProvidedOptions[key] = this.options[key];
1627 break;
1628 case 'safe':
1629 setSafe(this.options, value);
1630 this._userProvidedOptions[key] = this.options[key];
1631 break;
1632 case 'timestamps':
1633 this.setupTimestamp(value);
1634 this.options[key] = value;
1635 this._userProvidedOptions[key] = this.options[key];
1636 break;
1637 default:
1638 this.options[key] = value;
1639 this._userProvidedOptions[key] = this.options[key];
1640 break;
1641 }
1642
1643 return this;
1644};
1645
1646/*!
1647 * ignore
1648 */
1649
1650const safeDeprecationWarning = 'Mongoose: The `safe` option for schemas is ' +
1651 'deprecated. Use the `writeConcern` option instead: ' +
1652 'http://bit.ly/mongoose-write-concern';
1653
1654const setSafe = util.deprecate(function setSafe(options, value) {
1655 options.safe = value === false ?
1656 {w: 0} :
1657 value;
1658}, safeDeprecationWarning);
1659
1660/**
1661 * Gets a schema option.
1662 *
1663 * ####Example:
1664 *
1665 * schema.get('strict'); // true
1666 * schema.set('strict', false);
1667 * schema.get('strict'); // false
1668 *
1669 * @param {String} key option name
1670 * @api public
1671 * @return {Any} the option's value
1672 */
1673
1674Schema.prototype.get = function(key) {
1675 return this.options[key];
1676};
1677
1678/**
1679 * The allowed index types
1680 *
1681 * @receiver Schema
1682 * @static indexTypes
1683 * @api public
1684 */
1685
1686const indexTypes = '2d 2dsphere hashed text'.split(' ');
1687
1688Object.defineProperty(Schema, 'indexTypes', {
1689 get: function() {
1690 return indexTypes;
1691 },
1692 set: function() {
1693 throw new Error('Cannot overwrite Schema.indexTypes');
1694 }
1695});
1696
1697/**
1698 * Returns a list of indexes that this schema declares, via `schema.index()`
1699 * or by `index: true` in a path's options.
1700 *
1701 * ####Example:
1702 *
1703 * const userSchema = new Schema({
1704 * email: { type: String, required: true, unique: true },
1705 * registeredAt: { type: Date, index: true }
1706 * });
1707 *
1708 * // [ [ { email: 1 }, { unique: true, background: true } ],
1709 * // [ { registeredAt: 1 }, { background: true } ] ]
1710 * userSchema.indexes();
1711 *
1712 * @api public
1713 * @return {Array} list of indexes defined in the schema
1714 */
1715
1716Schema.prototype.indexes = function() {
1717 return getIndexes(this);
1718};
1719
1720/**
1721 * Creates a virtual type with the given name.
1722 *
1723 * @param {String} name
1724 * @param {Object} [options]
1725 * @param {String|Model} [options.ref] model name or model instance. Marks this as a [populate virtual](populate.html#populate-virtuals).
1726 * @param {String|Function} [options.localField] Required for populate virtuals. See [populate virtual docs](populate.html#populate-virtuals) for more information.
1727 * @param {String|Function} [options.foreignField] Required for populate virtuals. See [populate virtual docs](populate.html#populate-virtuals) for more information.
1728 * @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.
1729 * @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()`.
1730 * @return {VirtualType}
1731 */
1732
1733Schema.prototype.virtual = function(name, options) {
1734 if (name instanceof VirtualType) {
1735 return this.virtual(name.path, name.options);
1736 }
1737
1738 options = new VirtualOptions(options);
1739
1740 if (utils.hasUserDefinedProperty(options, ['ref', 'refPath'])) {
1741 if (options.localField == null) {
1742 throw new Error('Reference virtuals require `localField` option');
1743 }
1744
1745 if (options.foreignField == null) {
1746 throw new Error('Reference virtuals require `foreignField` option');
1747 }
1748
1749 this.pre('init', function(obj) {
1750 if (mpath.has(name, obj)) {
1751 const _v = mpath.get(name, obj);
1752 if (!this.$$populatedVirtuals) {
1753 this.$$populatedVirtuals = {};
1754 }
1755
1756 if (options.justOne || options.count) {
1757 this.$$populatedVirtuals[name] = Array.isArray(_v) ?
1758 _v[0] :
1759 _v;
1760 } else {
1761 this.$$populatedVirtuals[name] = Array.isArray(_v) ?
1762 _v :
1763 _v == null ? [] : [_v];
1764 }
1765
1766 mpath.unset(name, obj);
1767 }
1768 });
1769
1770 const virtual = this.virtual(name);
1771 virtual.options = options;
1772 return virtual.
1773 get(function() {
1774 if (!this.$$populatedVirtuals) {
1775 this.$$populatedVirtuals = {};
1776 }
1777 if (this.$$populatedVirtuals.hasOwnProperty(name)) {
1778 return this.$$populatedVirtuals[name];
1779 }
1780 return void 0;
1781 }).
1782 set(function(_v) {
1783 if (!this.$$populatedVirtuals) {
1784 this.$$populatedVirtuals = {};
1785 }
1786
1787 if (options.justOne || options.count) {
1788 this.$$populatedVirtuals[name] = Array.isArray(_v) ?
1789 _v[0] :
1790 _v;
1791
1792 if (typeof this.$$populatedVirtuals[name] !== 'object') {
1793 this.$$populatedVirtuals[name] = options.count ? _v : null;
1794 }
1795 } else {
1796 this.$$populatedVirtuals[name] = Array.isArray(_v) ?
1797 _v :
1798 _v == null ? [] : [_v];
1799
1800 this.$$populatedVirtuals[name] = this.$$populatedVirtuals[name].filter(function(doc) {
1801 return doc && typeof doc === 'object';
1802 });
1803 }
1804 });
1805 }
1806
1807 const virtuals = this.virtuals;
1808 const parts = name.split('.');
1809
1810 if (this.pathType(name) === 'real') {
1811 throw new Error('Virtual path "' + name + '"' +
1812 ' conflicts with a real path in the schema');
1813 }
1814
1815 virtuals[name] = parts.reduce(function(mem, part, i) {
1816 mem[part] || (mem[part] = (i === parts.length - 1)
1817 ? new VirtualType(options, name)
1818 : {});
1819 return mem[part];
1820 }, this.tree);
1821
1822 // Workaround for gh-8198: if virtual is under document array, make a fake
1823 // virtual. See gh-8210
1824 let cur = parts[0];
1825 for (let i = 0; i < parts.length - 1; ++i) {
1826 if (this.paths[cur] != null && this.paths[cur].$isMongooseDocumentArray) {
1827 const remnant = parts.slice(i + 1).join('.');
1828 const v = this.paths[cur].schema.virtual(remnant);
1829 v.get((v, virtual, doc) => {
1830 const parent = doc.__parentArray[arrayParentSymbol];
1831 const path = cur + '.' + doc.__index + '.' + remnant;
1832 return parent.get(path);
1833 });
1834 break;
1835 }
1836
1837 cur += '.' + parts[i + 1];
1838 }
1839
1840 return virtuals[name];
1841};
1842
1843/**
1844 * Returns the virtual type with the given `name`.
1845 *
1846 * @param {String} name
1847 * @return {VirtualType}
1848 */
1849
1850Schema.prototype.virtualpath = function(name) {
1851 return this.virtuals.hasOwnProperty(name) ? this.virtuals[name] : null;
1852};
1853
1854/**
1855 * Removes the given `path` (or [`paths`]).
1856 *
1857 * ####Example:
1858 *
1859 * const schema = new Schema({ name: String, age: Number });
1860 * schema.remove('name');
1861 * schema.path('name'); // Undefined
1862 * schema.path('age'); // SchemaNumber { ... }
1863 *
1864 * @param {String|Array} path
1865 * @return {Schema} the Schema instance
1866 * @api public
1867 */
1868Schema.prototype.remove = function(path) {
1869 if (typeof path === 'string') {
1870 path = [path];
1871 }
1872 if (Array.isArray(path)) {
1873 path.forEach(function(name) {
1874 if (this.path(name) == null && !this.nested[name]) {
1875 return;
1876 }
1877 if (this.nested[name]) {
1878 const allKeys = Object.keys(this.paths).
1879 concat(Object.keys(this.nested));
1880 for (const path of allKeys) {
1881 if (path.startsWith(name + '.')) {
1882 delete this.paths[path];
1883 delete this.nested[path];
1884 _deletePath(this, path);
1885 }
1886 }
1887
1888 delete this.nested[name];
1889 _deletePath(this, name);
1890 return;
1891 }
1892
1893 delete this.paths[name];
1894 _deletePath(this, name);
1895 }, this);
1896 }
1897 return this;
1898};
1899
1900/*!
1901 * ignore
1902 */
1903
1904function _deletePath(schema, name) {
1905 const pieces = name.split('.');
1906 const last = pieces.pop();
1907 let branch = schema.tree;
1908 for (let i = 0; i < pieces.length; ++i) {
1909 branch = branch[pieces[i]];
1910 }
1911 delete branch[last];
1912}
1913
1914/**
1915 * 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),
1916 * and [instance methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Class_body_and_method_definitions)
1917 * to schema [virtuals](http://mongoosejs.com/docs/guide.html#virtuals),
1918 * [statics](http://mongoosejs.com/docs/guide.html#statics), and
1919 * [methods](http://mongoosejs.com/docs/guide.html#methods).
1920 *
1921 * ####Example:
1922 *
1923 * ```javascript
1924 * const md5 = require('md5');
1925 * const userSchema = new Schema({ email: String });
1926 * class UserClass {
1927 * // `gravatarImage` becomes a virtual
1928 * get gravatarImage() {
1929 * const hash = md5(this.email.toLowerCase());
1930 * return `https://www.gravatar.com/avatar/${hash}`;
1931 * }
1932 *
1933 * // `getProfileUrl()` becomes a document method
1934 * getProfileUrl() {
1935 * return `https://mysite.com/${this.email}`;
1936 * }
1937 *
1938 * // `findByEmail()` becomes a static
1939 * static findByEmail(email) {
1940 * return this.findOne({ email });
1941 * }
1942 * }
1943 *
1944 * // `schema` will now have a `gravatarImage` virtual, a `getProfileUrl()` method,
1945 * // and a `findByEmail()` static
1946 * userSchema.loadClass(UserClass);
1947 * ```
1948 *
1949 * @param {Function} model
1950 * @param {Boolean} [virtualsOnly] if truthy, only pulls virtuals from the class, not methods or statics
1951 */
1952Schema.prototype.loadClass = function(model, virtualsOnly) {
1953 if (model === Object.prototype ||
1954 model === Function.prototype ||
1955 model.prototype.hasOwnProperty('$isMongooseModelPrototype')) {
1956 return this;
1957 }
1958
1959 this.loadClass(Object.getPrototypeOf(model));
1960
1961 // Add static methods
1962 if (!virtualsOnly) {
1963 Object.getOwnPropertyNames(model).forEach(function(name) {
1964 if (name.match(/^(length|name|prototype)$/)) {
1965 return;
1966 }
1967 const method = Object.getOwnPropertyDescriptor(model, name);
1968 if (typeof method.value === 'function') {
1969 this.static(name, method.value);
1970 }
1971 }, this);
1972 }
1973
1974 // Add methods and virtuals
1975 Object.getOwnPropertyNames(model.prototype).forEach(function(name) {
1976 if (name.match(/^(constructor)$/)) {
1977 return;
1978 }
1979 const method = Object.getOwnPropertyDescriptor(model.prototype, name);
1980 if (!virtualsOnly) {
1981 if (typeof method.value === 'function') {
1982 this.method(name, method.value);
1983 }
1984 }
1985 if (typeof method.get === 'function') {
1986 this.virtual(name).get(method.get);
1987 }
1988 if (typeof method.set === 'function') {
1989 this.virtual(name).set(method.set);
1990 }
1991 }, this);
1992
1993 return this;
1994};
1995
1996/*!
1997 * ignore
1998 */
1999
2000Schema.prototype._getSchema = function(path) {
2001 const _this = this;
2002 const pathschema = _this.path(path);
2003 const resultPath = [];
2004
2005 if (pathschema) {
2006 pathschema.$fullPath = path;
2007 return pathschema;
2008 }
2009
2010 function search(parts, schema) {
2011 let p = parts.length + 1;
2012 let foundschema;
2013 let trypath;
2014
2015 while (p--) {
2016 trypath = parts.slice(0, p).join('.');
2017 foundschema = schema.path(trypath);
2018 if (foundschema) {
2019 resultPath.push(trypath);
2020
2021 if (foundschema.caster) {
2022 // array of Mixed?
2023 if (foundschema.caster instanceof MongooseTypes.Mixed) {
2024 foundschema.caster.$fullPath = resultPath.join('.');
2025 return foundschema.caster;
2026 }
2027
2028 // Now that we found the array, we need to check if there
2029 // are remaining document paths to look up for casting.
2030 // Also we need to handle array.$.path since schema.path
2031 // doesn't work for that.
2032 // If there is no foundschema.schema we are dealing with
2033 // a path like array.$
2034 if (p !== parts.length && foundschema.schema) {
2035 let ret;
2036 if (parts[p] === '$' || isArrayFilter(parts[p])) {
2037 if (p + 1 === parts.length) {
2038 // comments.$
2039 return foundschema;
2040 }
2041 // comments.$.comments.$.title
2042 ret = search(parts.slice(p + 1), foundschema.schema);
2043 if (ret) {
2044 ret.$isUnderneathDocArray = ret.$isUnderneathDocArray ||
2045 !foundschema.schema.$isSingleNested;
2046 }
2047 return ret;
2048 }
2049 // this is the last path of the selector
2050 ret = search(parts.slice(p), foundschema.schema);
2051 if (ret) {
2052 ret.$isUnderneathDocArray = ret.$isUnderneathDocArray ||
2053 !foundschema.schema.$isSingleNested;
2054 }
2055 return ret;
2056 }
2057 }
2058
2059 foundschema.$fullPath = resultPath.join('.');
2060
2061 return foundschema;
2062 }
2063 }
2064 }
2065
2066 // look for arrays
2067 const parts = path.split('.');
2068 for (let i = 0; i < parts.length; ++i) {
2069 if (parts[i] === '$' || isArrayFilter(parts[i])) {
2070 // Re: gh-5628, because `schema.path()` doesn't take $ into account.
2071 parts[i] = '0';
2072 }
2073 }
2074 return search(parts, _this);
2075};
2076
2077/*!
2078 * ignore
2079 */
2080
2081Schema.prototype._getPathType = function(path) {
2082 const _this = this;
2083 const pathschema = _this.path(path);
2084
2085 if (pathschema) {
2086 return 'real';
2087 }
2088
2089 function search(parts, schema) {
2090 let p = parts.length + 1,
2091 foundschema,
2092 trypath;
2093
2094 while (p--) {
2095 trypath = parts.slice(0, p).join('.');
2096 foundschema = schema.path(trypath);
2097 if (foundschema) {
2098 if (foundschema.caster) {
2099 // array of Mixed?
2100 if (foundschema.caster instanceof MongooseTypes.Mixed) {
2101 return { schema: foundschema, pathType: 'mixed' };
2102 }
2103
2104 // Now that we found the array, we need to check if there
2105 // are remaining document paths to look up for casting.
2106 // Also we need to handle array.$.path since schema.path
2107 // doesn't work for that.
2108 // If there is no foundschema.schema we are dealing with
2109 // a path like array.$
2110 if (p !== parts.length && foundschema.schema) {
2111 if (parts[p] === '$' || isArrayFilter(parts[p])) {
2112 if (p === parts.length - 1) {
2113 return { schema: foundschema, pathType: 'nested' };
2114 }
2115 // comments.$.comments.$.title
2116 return search(parts.slice(p + 1), foundschema.schema);
2117 }
2118 // this is the last path of the selector
2119 return search(parts.slice(p), foundschema.schema);
2120 }
2121 return {
2122 schema: foundschema,
2123 pathType: foundschema.$isSingleNested ? 'nested' : 'array'
2124 };
2125 }
2126 return { schema: foundschema, pathType: 'real' };
2127 } else if (p === parts.length && schema.nested[trypath]) {
2128 return { schema: schema, pathType: 'nested' };
2129 }
2130 }
2131 return { schema: foundschema || schema, pathType: 'undefined' };
2132 }
2133
2134 // look for arrays
2135 return search(path.split('.'), _this);
2136};
2137
2138/*!
2139 * ignore
2140 */
2141
2142function isArrayFilter(piece) {
2143 return piece.startsWith('$[') && piece.endsWith(']');
2144}
2145
2146/*!
2147 * Module exports.
2148 */
2149
2150module.exports = exports = Schema;
2151
2152// require down here because of reference issues
2153
2154/**
2155 * The various built-in Mongoose Schema Types.
2156 *
2157 * ####Example:
2158 *
2159 * var mongoose = require('mongoose');
2160 * var ObjectId = mongoose.Schema.Types.ObjectId;
2161 *
2162 * ####Types:
2163 *
2164 * - [String](#schema-string-js)
2165 * - [Number](#schema-number-js)
2166 * - [Boolean](#schema-boolean-js) | Bool
2167 * - [Array](#schema-array-js)
2168 * - [Buffer](#schema-buffer-js)
2169 * - [Date](#schema-date-js)
2170 * - [ObjectId](#schema-objectid-js) | Oid
2171 * - [Mixed](#schema-mixed-js)
2172 *
2173 * Using this exposed access to the `Mixed` SchemaType, we can use them in our schema.
2174 *
2175 * var Mixed = mongoose.Schema.Types.Mixed;
2176 * new mongoose.Schema({ _user: Mixed })
2177 *
2178 * @api public
2179 */
2180
2181Schema.Types = MongooseTypes = require('./schema/index');
2182
2183/*!
2184 * ignore
2185 */
2186
2187exports.ObjectId = MongooseTypes.ObjectId;