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