UNPKG

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