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