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