1 | 'use strict';
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 | const EventEmitter = require('events').EventEmitter;
|
8 | const InternalCache = require('./internal');
|
9 | const MongooseError = require('./error');
|
10 | const MixedSchema = require('./schema/mixed');
|
11 | const ObjectExpectedError = require('./error/objectExpected');
|
12 | const ObjectParameterError = require('./error/objectParameter');
|
13 | const StrictModeError = require('./error/strict');
|
14 | const ValidatorError = require('./schematype').ValidatorError;
|
15 | const VirtualType = require('./virtualtype');
|
16 | const cleanModifiedSubpaths = require('./helpers/document/cleanModifiedSubpaths');
|
17 | const compile = require('./helpers/document/compile').compile;
|
18 | const defineKey = require('./helpers/document/compile').defineKey;
|
19 | const flatten = require('./helpers/common').flatten;
|
20 | const get = require('./helpers/get');
|
21 | const getEmbeddedDiscriminatorPath = require('./helpers/document/getEmbeddedDiscriminatorPath');
|
22 | const idGetter = require('./plugins/idGetter');
|
23 | const isDefiningProjection = require('./helpers/projection/isDefiningProjection');
|
24 | const isExclusive = require('./helpers/projection/isExclusive');
|
25 | const inspect = require('util').inspect;
|
26 | const internalToObjectOptions = require('./options').internalToObjectOptions;
|
27 | const mpath = require('mpath');
|
28 | const utils = require('./utils');
|
29 |
|
30 | const ValidationError = MongooseError.ValidationError;
|
31 | const clone = utils.clone;
|
32 | const deepEqual = utils.deepEqual;
|
33 | const isMongooseObject = utils.isMongooseObject;
|
34 |
|
35 | const arrayAtomicsSymbol = require('./helpers/symbols').arrayAtomicsSymbol;
|
36 | const documentArrayParent = require('./helpers/symbols').documentArrayParent;
|
37 | const documentSchemaSymbol = require('./helpers/symbols').documentSchemaSymbol;
|
38 | const getSymbol = require('./helpers/symbols').getSymbol;
|
39 | const populateModelSymbol = require('./helpers/symbols').populateModelSymbol;
|
40 |
|
41 | let DocumentArray;
|
42 | let MongooseArray;
|
43 | let Embedded;
|
44 |
|
45 | const specialProperties = utils.specialProperties;
|
46 |
|
47 | /**
|
48 | * The core Mongoose document constructor. You should not call this directly,
|
49 | * the Mongoose [Model constructor](./api.html#Model) calls this for you.
|
50 | *
|
51 | * @param {Object} obj the values to set
|
52 | * @param {Object} [fields] optional object containing the fields which were selected in the query returning this document and any populated paths data
|
53 | * @param {Boolean} [skipId] bool, should we auto create an ObjectId _id
|
54 | * @inherits NodeJS EventEmitter http:
|
55 | * @event `init`: Emitted on a document after it has was retreived from the db and fully hydrated by Mongoose.
|
56 | * @event `save`: Emitted when the document is successfully saved
|
57 | * @api private
|
58 | */
|
59 |
|
60 | function Document(obj, fields, skipId, options) {
|
61 | if (typeof skipId === 'object' && skipId != null) {
|
62 | options = skipId;
|
63 | skipId = options.skipId;
|
64 | }
|
65 | options = options || {};
|
66 |
|
67 | this.$__ = new InternalCache;
|
68 | this.$__.emitter = new EventEmitter();
|
69 | this.isNew = 'isNew' in options ? options.isNew : true;
|
70 | this.errors = undefined;
|
71 | this.$__.$options = options || {};
|
72 |
|
73 | if (obj != null && typeof obj !== 'object') {
|
74 | throw new ObjectParameterError(obj, 'obj', 'Document');
|
75 | }
|
76 |
|
77 | const schema = this.schema;
|
78 |
|
79 | if (typeof fields === 'boolean') {
|
80 | this.$__.strictMode = fields;
|
81 | fields = undefined;
|
82 | } else {
|
83 | this.$__.strictMode = schema.options.strict;
|
84 | this.$__.selected = fields;
|
85 | }
|
86 |
|
87 | const required = schema.requiredPaths(true);
|
88 | for (let i = 0; i < required.length; ++i) {
|
89 | this.$__.activePaths.require(required[i]);
|
90 | }
|
91 |
|
92 | this.$__.emitter.setMaxListeners(0);
|
93 |
|
94 | let exclude = null;
|
95 |
|
96 |
|
97 |
|
98 | if (utils.isPOJO(fields)) {
|
99 | exclude = isExclusive(fields);
|
100 | }
|
101 |
|
102 | const hasIncludedChildren = exclude === false && fields ?
|
103 | $__hasIncludedChildren(fields) :
|
104 | {};
|
105 |
|
106 | if (this._doc == null) {
|
107 | this.$__buildDoc(obj, fields, skipId, exclude, hasIncludedChildren, false);
|
108 |
|
109 |
|
110 |
|
111 | $__applyDefaults(this, fields, skipId, exclude, hasIncludedChildren, true, {
|
112 | isNew: this.isNew
|
113 | });
|
114 | }
|
115 |
|
116 | if (obj) {
|
117 | if (obj instanceof Document) {
|
118 | this.isNew = obj.isNew;
|
119 | }
|
120 |
|
121 | if (this.$__original_set) {
|
122 | this.$__original_set(obj, undefined, true);
|
123 | } else {
|
124 | this.$set(obj, undefined, true);
|
125 | }
|
126 | }
|
127 |
|
128 | // Function defaults get applied **after** setting initial values so they
|
129 | // see the full doc rather than an empty one, unless they opt out.
|
130 | // Re: gh-3781, gh-6155
|
131 | if (options.willInit) {
|
132 | this.once('init', () => {
|
133 | $__applyDefaults(this, fields, skipId, exclude, hasIncludedChildren, false, options.skipDefaults, {
|
134 | isNew: this.isNew
|
135 | });
|
136 | });
|
137 | } else {
|
138 | $__applyDefaults(this, fields, skipId, exclude, hasIncludedChildren, false, options.skipDefaults, {
|
139 | isNew: this.isNew
|
140 | });
|
141 | }
|
142 |
|
143 | this.$__._id = this._id;
|
144 | this.$locals = {};
|
145 |
|
146 | if (!schema.options.strict && obj) {
|
147 | const _this = this;
|
148 | const keys = Object.keys(this._doc);
|
149 |
|
150 | keys.forEach(function(key) {
|
151 | if (!(key in schema.tree)) {
|
152 | defineKey(key, null, _this);
|
153 | }
|
154 | });
|
155 | }
|
156 |
|
157 | applyQueue(this);
|
158 | }
|
159 |
|
160 |
|
161 |
|
162 |
|
163 |
|
164 | utils.each(
|
165 | ['on', 'once', 'emit', 'listeners', 'removeListener', 'setMaxListeners',
|
166 | 'removeAllListeners', 'addListener'],
|
167 | function(emitterFn) {
|
168 | Document.prototype[emitterFn] = function() {
|
169 | return this.$__.emitter[emitterFn].apply(this.$__.emitter, arguments);
|
170 | };
|
171 | });
|
172 |
|
173 | Document.prototype.constructor = Document;
|
174 |
|
175 |
|
176 |
|
177 |
|
178 |
|
179 |
|
180 |
|
181 |
|
182 |
|
183 |
|
184 | Document.prototype.schema;
|
185 |
|
186 |
|
187 |
|
188 |
|
189 |
|
190 |
|
191 |
|
192 |
|
193 |
|
194 |
|
195 |
|
196 |
|
197 |
|
198 |
|
199 |
|
200 |
|
201 |
|
202 |
|
203 |
|
204 |
|
205 |
|
206 |
|
207 |
|
208 |
|
209 | Object.defineProperty(Document.prototype, '$locals', {
|
210 | configurable: false,
|
211 | enumerable: false,
|
212 | writable: true
|
213 | });
|
214 |
|
215 |
|
216 |
|
217 |
|
218 |
|
219 |
|
220 |
|
221 |
|
222 |
|
223 |
|
224 | Document.prototype.isNew;
|
225 |
|
226 |
|
227 |
|
228 |
|
229 |
|
230 |
|
231 |
|
232 |
|
233 |
|
234 |
|
235 |
|
236 |
|
237 |
|
238 |
|
239 |
|
240 |
|
241 |
|
242 | Document.prototype.id;
|
243 |
|
244 |
|
245 |
|
246 |
|
247 |
|
248 |
|
249 |
|
250 |
|
251 |
|
252 |
|
253 | Document.prototype.errors;
|
254 |
|
255 |
|
256 |
|
257 |
|
258 |
|
259 | function $__hasIncludedChildren(fields) {
|
260 | const hasIncludedChildren = {};
|
261 | const keys = Object.keys(fields);
|
262 | for (let j = 0; j < keys.length; ++j) {
|
263 | const parts = keys[j].split('.');
|
264 | const c = [];
|
265 | for (let k = 0; k < parts.length; ++k) {
|
266 | c.push(parts[k]);
|
267 | hasIncludedChildren[c.join('.')] = 1;
|
268 | }
|
269 | }
|
270 |
|
271 | return hasIncludedChildren;
|
272 | }
|
273 |
|
274 |
|
275 |
|
276 |
|
277 |
|
278 | function $__applyDefaults(doc, fields, skipId, exclude, hasIncludedChildren, isBeforeSetters, pathsToSkip) {
|
279 | const paths = Object.keys(doc.schema.paths);
|
280 | const plen = paths.length;
|
281 |
|
282 | for (let i = 0; i < plen; ++i) {
|
283 | let def;
|
284 | let curPath = '';
|
285 | const p = paths[i];
|
286 |
|
287 | if (p === '_id' && skipId) {
|
288 | continue;
|
289 | }
|
290 |
|
291 | const type = doc.schema.paths[p];
|
292 | const path = p.split('.');
|
293 | const len = path.length;
|
294 | let included = false;
|
295 | let doc_ = doc._doc;
|
296 |
|
297 | for (let j = 0; j < len; ++j) {
|
298 | if (doc_ == null) {
|
299 | break;
|
300 | }
|
301 |
|
302 | const piece = path[j];
|
303 | curPath += (!curPath.length ? '' : '.') + piece;
|
304 |
|
305 | if (exclude === true) {
|
306 | if (curPath in fields) {
|
307 | break;
|
308 | }
|
309 | } else if (exclude === false && fields && !included) {
|
310 | if (curPath in fields) {
|
311 | included = true;
|
312 | } else if (!hasIncludedChildren[curPath]) {
|
313 | break;
|
314 | }
|
315 | }
|
316 |
|
317 | if (j === len - 1) {
|
318 | if (doc_[piece] !== void 0) {
|
319 | break;
|
320 | }
|
321 |
|
322 | if (typeof type.defaultValue === 'function') {
|
323 | if (!type.defaultValue.$runBeforeSetters && isBeforeSetters) {
|
324 | break;
|
325 | }
|
326 | if (type.defaultValue.$runBeforeSetters && !isBeforeSetters) {
|
327 | break;
|
328 | }
|
329 | } else if (!isBeforeSetters) {
|
330 |
|
331 | continue;
|
332 | }
|
333 |
|
334 | if (pathsToSkip && pathsToSkip[curPath]) {
|
335 | break;
|
336 | }
|
337 |
|
338 | if (fields && exclude !== null) {
|
339 | if (exclude === true) {
|
340 |
|
341 | if (p in fields) {
|
342 | continue;
|
343 | }
|
344 |
|
345 | def = type.getDefault(doc, false);
|
346 | if (typeof def !== 'undefined') {
|
347 | doc_[piece] = def;
|
348 | doc.$__.activePaths.default(p);
|
349 | }
|
350 | } else if (included) {
|
351 |
|
352 | def = type.getDefault(doc, false);
|
353 | if (typeof def !== 'undefined') {
|
354 | doc_[piece] = def;
|
355 | doc.$__.activePaths.default(p);
|
356 | }
|
357 | }
|
358 | } else {
|
359 | def = type.getDefault(doc, false);
|
360 | if (typeof def !== 'undefined') {
|
361 | doc_[piece] = def;
|
362 | doc.$__.activePaths.default(p);
|
363 | }
|
364 | }
|
365 | } else {
|
366 | doc_ = doc_[piece];
|
367 | }
|
368 | }
|
369 | }
|
370 | }
|
371 |
|
372 |
|
373 |
|
374 |
|
375 |
|
376 |
|
377 |
|
378 |
|
379 |
|
380 |
|
381 |
|
382 |
|
383 |
|
384 | Document.prototype.$__buildDoc = function(obj, fields, skipId, exclude, hasIncludedChildren) {
|
385 | const doc = {};
|
386 |
|
387 | const paths = Object.keys(this.schema.paths).
|
388 |
|
389 |
|
390 | filter(p => !p.includes('$*'));
|
391 | const plen = paths.length;
|
392 | let ii = 0;
|
393 |
|
394 | for (; ii < plen; ++ii) {
|
395 | const p = paths[ii];
|
396 |
|
397 | if (p === '_id') {
|
398 | if (skipId) {
|
399 | continue;
|
400 | }
|
401 | if (obj && '_id' in obj) {
|
402 | continue;
|
403 | }
|
404 | }
|
405 |
|
406 | const path = p.split('.');
|
407 | const len = path.length;
|
408 | const last = len - 1;
|
409 | let curPath = '';
|
410 | let doc_ = doc;
|
411 | let included = false;
|
412 |
|
413 | for (let i = 0; i < len; ++i) {
|
414 | const piece = path[i];
|
415 |
|
416 | curPath += (!curPath.length ? '' : '.') + piece;
|
417 |
|
418 |
|
419 | if (exclude === true) {
|
420 | if (curPath in fields) {
|
421 | break;
|
422 | }
|
423 | } else if (exclude === false && fields && !included) {
|
424 | if (curPath in fields) {
|
425 | included = true;
|
426 | } else if (!hasIncludedChildren[curPath]) {
|
427 | break;
|
428 | }
|
429 | }
|
430 |
|
431 | if (i < last) {
|
432 | doc_ = doc_[piece] || (doc_[piece] = {});
|
433 | }
|
434 | }
|
435 | }
|
436 |
|
437 | this._doc = doc;
|
438 | };
|
439 |
|
440 |
|
441 |
|
442 |
|
443 |
|
444 | Document.prototype.toBSON = function() {
|
445 | return this.toObject(internalToObjectOptions);
|
446 | };
|
447 |
|
448 |
|
449 |
|
450 |
|
451 |
|
452 |
|
453 |
|
454 |
|
455 |
|
456 |
|
457 |
|
458 |
|
459 |
|
460 |
|
461 |
|
462 |
|
463 | Document.prototype.init = function(doc, opts, fn) {
|
464 | if (typeof opts === 'function') {
|
465 | fn = opts;
|
466 | opts = null;
|
467 | }
|
468 |
|
469 | this.$__init(doc, opts);
|
470 |
|
471 | if (fn) {
|
472 | fn(null, this);
|
473 | }
|
474 |
|
475 | return this;
|
476 | };
|
477 |
|
478 |
|
479 |
|
480 |
|
481 |
|
482 | Document.prototype.$__init = function(doc, opts) {
|
483 | this.isNew = false;
|
484 | this.$init = true;
|
485 |
|
486 |
|
487 |
|
488 | if (doc._id !== null && doc._id !== undefined &&
|
489 | opts && opts.populated && opts.populated.length) {
|
490 | const id = String(doc._id);
|
491 | for (let i = 0; i < opts.populated.length; ++i) {
|
492 | const item = opts.populated[i];
|
493 | if (item.isVirtual) {
|
494 | this.populated(item.path, utils.getValue(item.path, doc), item);
|
495 | } else {
|
496 | this.populated(item.path, item._docs[id], item);
|
497 | }
|
498 | }
|
499 | }
|
500 |
|
501 | init(this, doc, this._doc);
|
502 |
|
503 | this.emit('init', this);
|
504 | this.constructor.emit('init', this);
|
505 |
|
506 | this.$__._id = this._id;
|
507 |
|
508 | return this;
|
509 | };
|
510 |
|
511 |
|
512 |
|
513 |
|
514 |
|
515 |
|
516 |
|
517 |
|
518 |
|
519 |
|
520 | function init(self, obj, doc, prefix) {
|
521 | prefix = prefix || '';
|
522 |
|
523 | const keys = Object.keys(obj);
|
524 | const len = keys.length;
|
525 | let schema;
|
526 | let path;
|
527 | let i;
|
528 | let index = 0;
|
529 |
|
530 | while (index < len) {
|
531 | _init(index++);
|
532 | }
|
533 |
|
534 | function _init(index) {
|
535 | i = keys[index];
|
536 | path = prefix + i;
|
537 | schema = self.schema.path(path);
|
538 |
|
539 |
|
540 |
|
541 |
|
542 | if (self.schema.$isRootDiscriminator && !self.isSelected(path)) {
|
543 | return;
|
544 | }
|
545 |
|
546 | if (!schema && utils.isPOJO(obj[i])) {
|
547 |
|
548 | if (!doc[i]) {
|
549 | doc[i] = {};
|
550 | }
|
551 | init(self, obj[i], doc[i], path + '.');
|
552 | } else if (!schema) {
|
553 | doc[i] = obj[i];
|
554 | } else {
|
555 | if (obj[i] === null) {
|
556 | doc[i] = null;
|
557 | } else if (obj[i] !== undefined) {
|
558 | const intCache = obj[i].$__ || {};
|
559 | const wasPopulated = intCache.wasPopulated || null;
|
560 | if (schema && !wasPopulated) {
|
561 | try {
|
562 | doc[i] = schema.cast(obj[i], self, true);
|
563 | } catch (e) {
|
564 | self.invalidate(e.path, new ValidatorError({
|
565 | path: e.path,
|
566 | message: e.message,
|
567 | type: 'cast',
|
568 | value: e.value
|
569 | }));
|
570 | }
|
571 | } else {
|
572 | doc[i] = obj[i];
|
573 | }
|
574 | }
|
575 |
|
576 | if (!self.isModified(path)) {
|
577 | self.$__.activePaths.init(path);
|
578 | }
|
579 | }
|
580 | }
|
581 | }
|
582 |
|
583 |
|
584 |
|
585 |
|
586 |
|
587 |
|
588 |
|
589 |
|
590 |
|
591 |
|
592 |
|
593 |
|
594 |
|
595 |
|
596 |
|
597 |
|
598 |
|
599 |
|
600 |
|
601 |
|
602 |
|
603 |
|
604 | Document.prototype.update = function update() {
|
605 | const args = utils.args(arguments);
|
606 | args.unshift({_id: this._id});
|
607 | const query = this.constructor.update.apply(this.constructor, args);
|
608 |
|
609 | if (this.$session() != null) {
|
610 | if (!('session' in query.options)) {
|
611 | query.options.session = this.$session();
|
612 | }
|
613 | }
|
614 |
|
615 | return query;
|
616 | };
|
617 |
|
618 |
|
619 |
|
620 |
|
621 |
|
622 |
|
623 |
|
624 |
|
625 |
|
626 |
|
627 |
|
628 |
|
629 |
|
630 |
|
631 |
|
632 |
|
633 |
|
634 |
|
635 |
|
636 |
|
637 |
|
638 |
|
639 | Document.prototype.updateOne = function updateOne(doc, options, callback) {
|
640 | const query = this.constructor.updateOne({_id: this._id}, doc, options);
|
641 | query._pre(cb => {
|
642 | this.constructor._middleware.execPre('updateOne', this, [], cb);
|
643 | });
|
644 | query._post(cb => {
|
645 | this.constructor._middleware.execPost('updateOne', this, [], {}, cb);
|
646 | });
|
647 |
|
648 | if (this.$session() != null) {
|
649 | if (!('session' in query.options)) {
|
650 | query.options.session = this.$session();
|
651 | }
|
652 | }
|
653 |
|
654 | if (callback != null) {
|
655 | return query.exec(callback);
|
656 | }
|
657 |
|
658 | return query;
|
659 | };
|
660 |
|
661 |
|
662 |
|
663 |
|
664 |
|
665 |
|
666 |
|
667 |
|
668 |
|
669 |
|
670 |
|
671 |
|
672 |
|
673 |
|
674 |
|
675 |
|
676 |
|
677 |
|
678 | Document.prototype.replaceOne = function replaceOne() {
|
679 | const args = utils.args(arguments);
|
680 | args.unshift({ _id: this._id });
|
681 | return this.constructor.replaceOne.apply(this.constructor, args);
|
682 | };
|
683 |
|
684 |
|
685 |
|
686 |
|
687 |
|
688 |
|
689 |
|
690 |
|
691 |
|
692 |
|
693 |
|
694 |
|
695 |
|
696 |
|
697 |
|
698 |
|
699 |
|
700 |
|
701 |
|
702 |
|
703 |
|
704 |
|
705 |
|
706 |
|
707 | Document.prototype.$session = function $session(session) {
|
708 | if (arguments.length === 0) {
|
709 | return this.$__.session;
|
710 | }
|
711 | this.$__.session = session;
|
712 |
|
713 | if (!this.ownerDocument) {
|
714 | const subdocs = this.$__getAllSubdocs();
|
715 | for (const child of subdocs) {
|
716 | child.$session(session);
|
717 | }
|
718 | }
|
719 |
|
720 | return session;
|
721 | };
|
722 |
|
723 |
|
724 |
|
725 |
|
726 |
|
727 |
|
728 |
|
729 |
|
730 |
|
731 |
|
732 |
|
733 |
|
734 |
|
735 |
|
736 | Document.prototype.overwrite = function overwrite(obj) {
|
737 | const keys = Array.from(new Set(Object.keys(this._doc).concat(Object.keys(obj))));
|
738 |
|
739 | for (const key of keys) {
|
740 | if (key === '_id') {
|
741 | continue;
|
742 | }
|
743 |
|
744 | if (this.schema.options.versionKey && key === this.schema.options.versionKey) {
|
745 | continue;
|
746 | }
|
747 | this.$set(key, obj[key]);
|
748 | }
|
749 |
|
750 | return this;
|
751 | };
|
752 |
|
753 | /**
|
754 | * Alias for `set()`, used internally to avoid conflicts
|
755 | *
|
756 | * @param {String|Object} path path or object of key/vals to set
|
757 | * @param {Any} val the value to set
|
758 | * @param {Schema|String|Number|Buffer|*} [type] optionally specify a type for "on-the-fly" attributes
|
759 | * @param {Object} [options] optionally specify options that modify the behavior of the set
|
760 | * @method $set
|
761 | * @name $set
|
762 | * @memberOf Document
|
763 | * @instance
|
764 | * @api public
|
765 | */
|
766 |
|
767 | Document.prototype.$set = function $set(path, val, type, options) {
|
768 | if (utils.isPOJO(type)) {
|
769 | options = type;
|
770 | type = undefined;
|
771 | }
|
772 |
|
773 | options = options || {};
|
774 | const merge = options.merge;
|
775 | const adhoc = type && type !== true;
|
776 | const constructing = type === true;
|
777 | let adhocs;
|
778 | let keys;
|
779 | let i = 0;
|
780 | let pathtype;
|
781 | let key;
|
782 | let prefix;
|
783 |
|
784 | const strict = 'strict' in options
|
785 | ? options.strict
|
786 | : this.$__.strictMode;
|
787 |
|
788 | if (adhoc) {
|
789 | adhocs = this.$__.adhocPaths || (this.$__.adhocPaths = {});
|
790 | adhocs[path] = this.schema.interpretAsType(path, type, this.schema.options);
|
791 | }
|
792 |
|
793 | if (typeof path !== 'string') {
|
794 |
|
795 | if (path === null || path === void 0) {
|
796 | const _ = path;
|
797 | path = val;
|
798 | val = _;
|
799 | } else {
|
800 | prefix = val ? val + '.' : '';
|
801 |
|
802 | if (path instanceof Document) {
|
803 | if (path.$__isNested) {
|
804 | path = path.toObject();
|
805 | } else {
|
806 | path = path._doc;
|
807 | }
|
808 | }
|
809 |
|
810 | keys = Object.keys(path);
|
811 | const len = keys.length;
|
812 |
|
813 | if (len === 0 && !this.schema.options.minimize) {
|
814 | if (val) {
|
815 | this.$set(val, {});
|
816 | }
|
817 | return this;
|
818 | }
|
819 |
|
820 | while (i < len) {
|
821 | _handleIndex.call(this, i++);
|
822 | }
|
823 |
|
824 | return this;
|
825 | }
|
826 | } else {
|
827 | this.$__.$setCalled.add(path);
|
828 | }
|
829 |
|
830 | function _handleIndex(i) {
|
831 | key = keys[i];
|
832 | const pathName = prefix + key;
|
833 | pathtype = this.schema.pathType(pathName);
|
834 |
|
835 |
|
836 |
|
837 | if (type === true &&
|
838 | !prefix &&
|
839 | path[key] != null &&
|
840 | pathtype === 'nested' &&
|
841 | this._doc[key] != null &&
|
842 | Object.keys(this._doc[key]).length === 0) {
|
843 | delete this._doc[key];
|
844 | }
|
845 |
|
846 | if (typeof path[key] === 'object' &&
|
847 | !utils.isNativeObject(path[key]) &&
|
848 | path[key] != null &&
|
849 | pathtype !== 'virtual' &&
|
850 | pathtype !== 'real' &&
|
851 | !(this.$__path(pathName) instanceof MixedSchema) &&
|
852 | !(this.schema.paths[pathName] &&
|
853 | this.schema.paths[pathName].options &&
|
854 | this.schema.paths[pathName].options.ref)) {
|
855 | this.$__.$setCalled.add(prefix + key);
|
856 | this.$set(path[key], prefix + key, constructing);
|
857 | } else if (strict) {
|
858 |
|
859 | if (constructing && path[key] === void 0 &&
|
860 | this.get(key) !== void 0) {
|
861 | return;
|
862 | }
|
863 |
|
864 | if (pathtype === 'adhocOrUndefined') {
|
865 | pathtype = getEmbeddedDiscriminatorPath(this, pathName, { typeOnly: true });
|
866 | }
|
867 |
|
868 | if (pathtype === 'real' || pathtype === 'virtual') {
|
869 |
|
870 | let p = path[key];
|
871 | if (this.schema.paths[pathName] &&
|
872 | this.schema.paths[pathName].$isSingleNested &&
|
873 | path[key] instanceof Document) {
|
874 | p = p.toObject({ virtuals: false, transform: false });
|
875 | }
|
876 | this.$set(prefix + key, p, constructing);
|
877 | } else if (pathtype === 'nested' && path[key] instanceof Document) {
|
878 | this.$set(prefix + key,
|
879 | path[key].toObject({transform: false}), constructing);
|
880 | } else if (strict === 'throw') {
|
881 | if (pathtype === 'nested') {
|
882 | throw new ObjectExpectedError(key, path[key]);
|
883 | } else {
|
884 | throw new StrictModeError(key);
|
885 | }
|
886 | }
|
887 | } else if (path[key] !== void 0) {
|
888 | this.$set(prefix + key, path[key], constructing);
|
889 | }
|
890 | }
|
891 |
|
892 | let pathType = this.schema.pathType(path);
|
893 | if (pathType === 'adhocOrUndefined') {
|
894 | pathType = getEmbeddedDiscriminatorPath(this, path, { typeOnly: true });
|
895 | }
|
896 |
|
897 |
|
898 |
|
899 | if (utils.isPOJO(val) && val.$__ != null && val._doc != null) {
|
900 | val = val._doc;
|
901 | }
|
902 |
|
903 | if (pathType === 'nested' && val) {
|
904 | if (typeof val === 'object' && val != null) {
|
905 | if (!merge) {
|
906 | this.$__setValue(path, null);
|
907 | cleanModifiedSubpaths(this, path);
|
908 | } else {
|
909 | return this.$set(val, path, constructing);
|
910 | }
|
911 |
|
912 | const keys = Object.keys(val);
|
913 | this.$__setValue(path, {});
|
914 | for (const key of keys) {
|
915 | this.$set(path + '.' + key, val[key], constructing);
|
916 | }
|
917 | this.markModified(path);
|
918 | cleanModifiedSubpaths(this, path, { skipDocArrays: true });
|
919 | return this;
|
920 | }
|
921 | this.invalidate(path, new MongooseError.CastError('Object', val, path));
|
922 | return this;
|
923 | }
|
924 |
|
925 | let schema;
|
926 | const parts = path.split('.');
|
927 |
|
928 |
|
929 | if (typeof this.schema.aliases[parts[0]] == 'string') {
|
930 | parts[0] = this.schema.aliases[parts[0]];
|
931 | }
|
932 |
|
933 | if (pathType === 'adhocOrUndefined' && strict) {
|
934 |
|
935 | let mixed;
|
936 |
|
937 | for (i = 0; i < parts.length; ++i) {
|
938 | const subpath = parts.slice(0, i + 1).join('.');
|
939 |
|
940 |
|
941 | if (i + 1 < parts.length && this.schema.pathType(subpath) === 'virtual') {
|
942 | mpath.set(path, val, this);
|
943 | return this;
|
944 | }
|
945 |
|
946 | schema = this.schema.path(subpath);
|
947 | if (schema == null) {
|
948 | continue;
|
949 | }
|
950 |
|
951 | if (schema instanceof MixedSchema) {
|
952 |
|
953 | mixed = true;
|
954 | break;
|
955 | }
|
956 | }
|
957 |
|
958 | if (schema == null) {
|
959 |
|
960 | schema = getEmbeddedDiscriminatorPath(this, path);
|
961 | }
|
962 |
|
963 | if (!mixed && !schema) {
|
964 | if (strict === 'throw') {
|
965 | throw new StrictModeError(path);
|
966 | }
|
967 | return this;
|
968 | }
|
969 | } else if (pathType === 'virtual') {
|
970 | schema = this.schema.virtualpath(path);
|
971 | schema.applySetters(val, this);
|
972 | return this;
|
973 | } else {
|
974 | schema = this.$__path(path);
|
975 | }
|
976 |
|
977 |
|
978 | let cur = this._doc;
|
979 | let curPath = '';
|
980 | for (i = 0; i < parts.length - 1; ++i) {
|
981 | cur = cur[parts[i]];
|
982 | curPath += (curPath.length > 0 ? '.' : '') + parts[i];
|
983 | if (!cur) {
|
984 | this.$set(curPath, {});
|
985 |
|
986 |
|
987 |
|
988 |
|
989 |
|
990 | if (!this.isSelected(curPath)) {
|
991 | this.unmarkModified(curPath);
|
992 | }
|
993 | cur = this.$__getValue(curPath);
|
994 | }
|
995 | }
|
996 |
|
997 | let pathToMark;
|
998 |
|
999 |
|
1000 |
|
1001 |
|
1002 | if (parts.length <= 1) {
|
1003 | pathToMark = path;
|
1004 | } else {
|
1005 | for (i = 0; i < parts.length; ++i) {
|
1006 | const subpath = parts.slice(0, i + 1).join('.');
|
1007 | if (this.get(subpath) === null) {
|
1008 | pathToMark = subpath;
|
1009 | break;
|
1010 | }
|
1011 | }
|
1012 |
|
1013 | if (!pathToMark) {
|
1014 | pathToMark = path;
|
1015 | }
|
1016 | }
|
1017 |
|
1018 |
|
1019 | const priorVal = (() => {
|
1020 | if (this.$__.$options.priorDoc != null) {
|
1021 | return this.$__.$options.priorDoc.$__getValue(path);
|
1022 | }
|
1023 | if (constructing) {
|
1024 | return void 0;
|
1025 | }
|
1026 | return this.$__getValue(path);
|
1027 | })();
|
1028 |
|
1029 | if (!schema) {
|
1030 | this.$__set(pathToMark, path, constructing, parts, schema, val, priorVal);
|
1031 | return this;
|
1032 | }
|
1033 |
|
1034 | let shouldSet = true;
|
1035 | try {
|
1036 |
|
1037 |
|
1038 | const refMatches = (() => {
|
1039 | if (schema.options == null) {
|
1040 | return false;
|
1041 | }
|
1042 | if (!(val instanceof Document)) {
|
1043 | return false;
|
1044 | }
|
1045 | const model = val.constructor;
|
1046 |
|
1047 |
|
1048 | const ref = schema.options.ref;
|
1049 | if (ref != null && (ref === model.modelName || ref === model.baseModelName)) {
|
1050 | return true;
|
1051 | }
|
1052 |
|
1053 |
|
1054 | const refPath = schema.options.refPath;
|
1055 | if (refPath == null) {
|
1056 | return false;
|
1057 | }
|
1058 | const modelName = val.get(refPath);
|
1059 | if (modelName === model.modelName || modelName === model.baseModelName) {
|
1060 | return true;
|
1061 | }
|
1062 | return false;
|
1063 | })();
|
1064 |
|
1065 | let didPopulate = false;
|
1066 | if (refMatches && val instanceof Document) {
|
1067 | if (this.ownerDocument) {
|
1068 | this.ownerDocument().populated(this.$__fullPath(path),
|
1069 | val._id, { [populateModelSymbol]: val.constructor });
|
1070 | } else {
|
1071 | this.populated(path, val._id, { [populateModelSymbol]: val.constructor });
|
1072 | }
|
1073 | didPopulate = true;
|
1074 | }
|
1075 |
|
1076 | let popOpts;
|
1077 | if (schema.options &&
|
1078 | Array.isArray(schema.options[this.schema.options.typeKey]) &&
|
1079 | schema.options[this.schema.options.typeKey].length &&
|
1080 | schema.options[this.schema.options.typeKey][0].ref &&
|
1081 | Array.isArray(val) &&
|
1082 | val.length > 0 &&
|
1083 | val[0] instanceof Document &&
|
1084 | val[0].constructor.modelName &&
|
1085 | (schema.options[this.schema.options.typeKey][0].ref === val[0].constructor.baseModelName || schema.options[this.schema.options.typeKey][0].ref === val[0].constructor.modelName)) {
|
1086 | if (this.ownerDocument) {
|
1087 | popOpts = { [populateModelSymbol]: val[0].constructor };
|
1088 | this.ownerDocument().populated(this.$__fullPath(path),
|
1089 | val.map(function(v) { return v._id; }), popOpts);
|
1090 | } else {
|
1091 | popOpts = { [populateModelSymbol]: val[0].constructor };
|
1092 | this.populated(path, val.map(function(v) { return v._id; }), popOpts);
|
1093 | }
|
1094 | didPopulate = true;
|
1095 | }
|
1096 |
|
1097 |
|
1098 |
|
1099 |
|
1100 |
|
1101 | if (this.schema.singleNestedPaths[path] == null) {
|
1102 | val = schema.applySetters(val, this, false, priorVal);
|
1103 | }
|
1104 |
|
1105 | if (!didPopulate && this.$__.populated) {
|
1106 | delete this.$__.populated[path];
|
1107 | }
|
1108 |
|
1109 | this.$markValid(path);
|
1110 | } catch (e) {
|
1111 | this.invalidate(path,
|
1112 | new MongooseError.CastError(schema.instance, val, path, e));
|
1113 | shouldSet = false;
|
1114 | }
|
1115 |
|
1116 | if (shouldSet) {
|
1117 | this.$__set(pathToMark, path, constructing, parts, schema, val, priorVal);
|
1118 | }
|
1119 |
|
1120 | if (schema.$isSingleNested && (this.isDirectModified(path) || val == null)) {
|
1121 | cleanModifiedSubpaths(this, path);
|
1122 | }
|
1123 |
|
1124 | return this;
|
1125 | };
|
1126 |
|
1127 |
|
1128 |
|
1129 |
|
1130 |
|
1131 |
|
1132 |
|
1133 |
|
1134 |
|
1135 |
|
1136 |
|
1137 |
|
1138 |
|
1139 |
|
1140 |
|
1141 |
|
1142 |
|
1143 |
|
1144 |
|
1145 |
|
1146 |
|
1147 |
|
1148 |
|
1149 |
|
1150 |
|
1151 |
|
1152 |
|
1153 |
|
1154 |
|
1155 |
|
1156 |
|
1157 |
|
1158 |
|
1159 |
|
1160 |
|
1161 |
|
1162 | Document.prototype.set = Document.prototype.$set;
|
1163 |
|
1164 | /**
|
1165 | * Determine if we should mark this change as modified.
|
1166 | *
|
1167 | * @return {Boolean}
|
1168 | * @api private
|
1169 | * @method $__shouldModify
|
1170 | * @memberOf Document
|
1171 | * @instance
|
1172 | */
|
1173 |
|
1174 | Document.prototype.$__shouldModify = function(pathToMark, path, constructing, parts, schema, val, priorVal) {
|
1175 | if (this.isNew) {
|
1176 | return true;
|
1177 | }
|
1178 |
|
1179 |
|
1180 |
|
1181 |
|
1182 | if (this.schema.singleNestedPaths[path] != null) {
|
1183 | return false;
|
1184 | }
|
1185 |
|
1186 | if (val === void 0 && !this.isSelected(path)) {
|
1187 |
|
1188 |
|
1189 | return true;
|
1190 | }
|
1191 |
|
1192 | if (val === void 0 && path in this.$__.activePaths.states.default) {
|
1193 |
|
1194 | return false;
|
1195 | }
|
1196 |
|
1197 |
|
1198 |
|
1199 | if (this.populated(path) &&
|
1200 | val instanceof Document &&
|
1201 | deepEqual(val._id, priorVal)) {
|
1202 | return false;
|
1203 | }
|
1204 |
|
1205 | if (!deepEqual(val, priorVal || this.get(path))) {
|
1206 | return true;
|
1207 | }
|
1208 |
|
1209 | if (!constructing &&
|
1210 | val !== null &&
|
1211 | val !== undefined &&
|
1212 | path in this.$__.activePaths.states.default &&
|
1213 | deepEqual(val, schema.getDefault(this, constructing))) {
|
1214 |
|
1215 |
|
1216 | return true;
|
1217 | }
|
1218 | return false;
|
1219 | };
|
1220 |
|
1221 |
|
1222 |
|
1223 |
|
1224 |
|
1225 |
|
1226 |
|
1227 |
|
1228 |
|
1229 |
|
1230 | Document.prototype.$__set = function(pathToMark, path, constructing, parts, schema, val, priorVal) {
|
1231 | Embedded = Embedded || require('./types/embedded');
|
1232 |
|
1233 | const shouldModify = this.$__shouldModify(pathToMark, path, constructing, parts,
|
1234 | schema, val, priorVal);
|
1235 | const _this = this;
|
1236 |
|
1237 | if (shouldModify) {
|
1238 | this.markModified(pathToMark);
|
1239 |
|
1240 |
|
1241 | MongooseArray || (MongooseArray = require('./types/array'));
|
1242 | if (val && val.isMongooseArray) {
|
1243 | val._registerAtomic('$set', val);
|
1244 |
|
1245 |
|
1246 | if (val.isMongooseDocumentArray) {
|
1247 | val.forEach(function(item) {
|
1248 | item && item.__parentArray && (item.__parentArray = val);
|
1249 | });
|
1250 | }
|
1251 |
|
1252 |
|
1253 |
|
1254 | this.$__.activePaths.forEach(function(modifiedPath) {
|
1255 | if (modifiedPath.startsWith(path + '.')) {
|
1256 | _this.$__.activePaths.ignore(modifiedPath);
|
1257 | }
|
1258 | });
|
1259 | }
|
1260 | }
|
1261 |
|
1262 | let obj = this._doc;
|
1263 | let i = 0;
|
1264 | const l = parts.length;
|
1265 | let cur = '';
|
1266 |
|
1267 | for (; i < l; i++) {
|
1268 | const next = i + 1;
|
1269 | const last = next === l;
|
1270 | cur += (cur ? '.' + parts[i] : parts[i]);
|
1271 | if (specialProperties.has(parts[i])) {
|
1272 | return;
|
1273 | }
|
1274 |
|
1275 | if (last) {
|
1276 | if (obj instanceof Map) {
|
1277 | obj.set(parts[i], val);
|
1278 | } else {
|
1279 | obj[parts[i]] = val;
|
1280 | }
|
1281 | } else {
|
1282 | if (utils.isPOJO(obj[parts[i]])) {
|
1283 | obj = obj[parts[i]];
|
1284 | } else if (obj[parts[i]] && obj[parts[i]] instanceof Embedded) {
|
1285 | obj = obj[parts[i]];
|
1286 | } else if (obj[parts[i]] && obj[parts[i]].$isSingleNested) {
|
1287 | obj = obj[parts[i]];
|
1288 | } else if (obj[parts[i]] && Array.isArray(obj[parts[i]])) {
|
1289 | obj = obj[parts[i]];
|
1290 | } else {
|
1291 | obj[parts[i]] = obj[parts[i]] || {};
|
1292 | obj = obj[parts[i]];
|
1293 | }
|
1294 | }
|
1295 | }
|
1296 | };
|
1297 |
|
1298 |
|
1299 |
|
1300 |
|
1301 |
|
1302 |
|
1303 |
|
1304 |
|
1305 | Document.prototype.$__getValue = function(path) {
|
1306 | return utils.getValue(path, this._doc);
|
1307 | };
|
1308 |
|
1309 |
|
1310 |
|
1311 |
|
1312 |
|
1313 |
|
1314 |
|
1315 |
|
1316 |
|
1317 | Document.prototype.$__setValue = function(path, val) {
|
1318 | utils.setValue(path, val, this._doc);
|
1319 | return this;
|
1320 | };
|
1321 |
|
1322 |
|
1323 |
|
1324 |
|
1325 |
|
1326 |
|
1327 |
|
1328 |
|
1329 |
|
1330 |
|
1331 |
|
1332 |
|
1333 |
|
1334 |
|
1335 |
|
1336 |
|
1337 |
|
1338 |
|
1339 |
|
1340 |
|
1341 | Document.prototype.get = function(path, type, options) {
|
1342 | let adhoc;
|
1343 | options = options || {};
|
1344 | if (type) {
|
1345 | adhoc = this.schema.interpretAsType(path, type, this.schema.options);
|
1346 | }
|
1347 |
|
1348 | const schema = this.$__path(path) || this.schema.virtualpath(path);
|
1349 | const pieces = path.split('.');
|
1350 | let obj = this._doc;
|
1351 |
|
1352 | if (schema instanceof VirtualType) {
|
1353 | if (schema.getters.length === 0) {
|
1354 | return void 0;
|
1355 | }
|
1356 | return schema.applyGetters(null, this);
|
1357 | }
|
1358 |
|
1359 |
|
1360 | if (typeof this.schema.aliases[pieces[0]] == 'string') {
|
1361 | pieces[0] = this.schema.aliases[pieces[0]];
|
1362 | }
|
1363 |
|
1364 | for (let i = 0, l = pieces.length; i < l; i++) {
|
1365 | if (obj && obj._doc) {
|
1366 | obj = obj._doc;
|
1367 | }
|
1368 |
|
1369 | if (obj == null) {
|
1370 | obj = void 0;
|
1371 | } else if (obj instanceof Map) {
|
1372 | obj = obj.get(pieces[i]);
|
1373 | } else if (i === l - 1) {
|
1374 | obj = utils.getValue(pieces[i], obj);
|
1375 | } else {
|
1376 | obj = obj[pieces[i]];
|
1377 | }
|
1378 | }
|
1379 |
|
1380 | if (adhoc) {
|
1381 | obj = adhoc.cast(obj);
|
1382 | }
|
1383 |
|
1384 | if (schema != null && options.getters !== false) {
|
1385 | obj = schema.applyGetters(obj, this);
|
1386 | } else if (this.schema.nested[path] && options.virtuals) {
|
1387 |
|
1388 | return applyGetters(this, utils.clone(obj) || {}, 'virtuals', { path: path });
|
1389 | }
|
1390 |
|
1391 | return obj;
|
1392 | };
|
1393 |
|
1394 |
|
1395 |
|
1396 |
|
1397 |
|
1398 | Document.prototype[getSymbol] = Document.prototype.get;
|
1399 |
|
1400 |
|
1401 |
|
1402 |
|
1403 |
|
1404 |
|
1405 |
|
1406 |
|
1407 |
|
1408 |
|
1409 |
|
1410 | Document.prototype.$__path = function(path) {
|
1411 | const adhocs = this.$__.adhocPaths;
|
1412 | const adhocType = adhocs && adhocs.hasOwnProperty(path) ? adhocs[path] : null;
|
1413 |
|
1414 | if (adhocType) {
|
1415 | return adhocType;
|
1416 | }
|
1417 | return this.schema.path(path);
|
1418 | };
|
1419 |
|
1420 |
|
1421 |
|
1422 |
|
1423 |
|
1424 |
|
1425 |
|
1426 |
|
1427 |
|
1428 |
|
1429 |
|
1430 |
|
1431 |
|
1432 |
|
1433 |
|
1434 |
|
1435 |
|
1436 | Document.prototype.markModified = function(path, scope) {
|
1437 | this.$__.activePaths.modify(path);
|
1438 | if (scope != null && !this.ownerDocument) {
|
1439 | this.$__.pathsToScopes[path] = scope;
|
1440 | }
|
1441 | };
|
1442 |
|
1443 |
|
1444 |
|
1445 |
|
1446 |
|
1447 |
|
1448 |
|
1449 |
|
1450 |
|
1451 |
|
1452 |
|
1453 |
|
1454 |
|
1455 |
|
1456 | Document.prototype.unmarkModified = function(path) {
|
1457 | this.$__.activePaths.init(path);
|
1458 | delete this.$__.pathsToScopes[path];
|
1459 | };
|
1460 |
|
1461 |
|
1462 |
|
1463 |
|
1464 |
|
1465 |
|
1466 |
|
1467 |
|
1468 |
|
1469 |
|
1470 |
|
1471 |
|
1472 |
|
1473 |
|
1474 |
|
1475 |
|
1476 |
|
1477 | Document.prototype.$ignore = function(path) {
|
1478 | this.$__.activePaths.ignore(path);
|
1479 | };
|
1480 |
|
1481 |
|
1482 |
|
1483 |
|
1484 |
|
1485 |
|
1486 |
|
1487 |
|
1488 |
|
1489 |
|
1490 |
|
1491 |
|
1492 |
|
1493 |
|
1494 |
|
1495 |
|
1496 |
|
1497 |
|
1498 |
|
1499 |
|
1500 |
|
1501 |
|
1502 |
|
1503 | Document.prototype.directModifiedPaths = function() {
|
1504 | return Object.keys(this.$__.activePaths.states.modify);
|
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 | Document.prototype.$isEmpty = function(path) {
|
1531 | const isEmptyOptions = {
|
1532 | minimize: true,
|
1533 | virtuals: false,
|
1534 | getters: false,
|
1535 | transform: false
|
1536 | };
|
1537 |
|
1538 | if (arguments.length > 0) {
|
1539 | const v = this.get(path);
|
1540 | if (v == null) {
|
1541 | return true;
|
1542 | }
|
1543 | if (typeof v !== 'object') {
|
1544 | return false;
|
1545 | }
|
1546 | if (utils.isPOJO(v)) {
|
1547 | return _isEmpty(v);
|
1548 | }
|
1549 | return Object.keys(v.toObject(isEmptyOptions)).length === 0;
|
1550 | }
|
1551 |
|
1552 | return Object.keys(this.toObject(isEmptyOptions)).length === 0;
|
1553 | };
|
1554 |
|
1555 | function _isEmpty(v) {
|
1556 | if (v == null) {
|
1557 | return true;
|
1558 | }
|
1559 | if (typeof v !== 'object' || Array.isArray(v)) {
|
1560 | return false;
|
1561 | }
|
1562 | for (const key of Object.keys(v)) {
|
1563 | if (!_isEmpty(v[key])) {
|
1564 | return false;
|
1565 | }
|
1566 | }
|
1567 | return true;
|
1568 | }
|
1569 |
|
1570 |
|
1571 |
|
1572 |
|
1573 |
|
1574 |
|
1575 |
|
1576 |
|
1577 |
|
1578 |
|
1579 | Document.prototype.modifiedPaths = function(options) {
|
1580 | options = options || {};
|
1581 | const directModifiedPaths = Object.keys(this.$__.activePaths.states.modify);
|
1582 | const _this = this;
|
1583 | return directModifiedPaths.reduce(function(list, path) {
|
1584 | const parts = path.split('.');
|
1585 | list = list.concat(parts.reduce(function(chains, part, i) {
|
1586 | return chains.concat(parts.slice(0, i).concat(part).join('.'));
|
1587 | }, []).filter(function(chain) {
|
1588 | return (list.indexOf(chain) === -1);
|
1589 | }));
|
1590 |
|
1591 | if (!options.includeChildren) {
|
1592 | return list;
|
1593 | }
|
1594 |
|
1595 | let cur = _this.get(path);
|
1596 | if (cur != null && typeof cur === 'object') {
|
1597 | if (cur._doc) {
|
1598 | cur = cur._doc;
|
1599 | }
|
1600 | if (Array.isArray(cur)) {
|
1601 | const len = cur.length;
|
1602 | for (let i = 0; i < len; ++i) {
|
1603 | if (list.indexOf(path + '.' + i) === -1) {
|
1604 | list.push(path + '.' + i);
|
1605 | if (cur[i] != null && cur[i].$__) {
|
1606 | const modified = cur[i].modifiedPaths();
|
1607 | for (const childPath of modified) {
|
1608 | list.push(path + '.' + i + '.' + childPath);
|
1609 | }
|
1610 | }
|
1611 | }
|
1612 | }
|
1613 | } else {
|
1614 | Object.keys(cur).
|
1615 | filter(function(key) {
|
1616 | return list.indexOf(path + '.' + key) === -1;
|
1617 | }).
|
1618 | forEach(function(key) {
|
1619 | list.push(path + '.' + key);
|
1620 | });
|
1621 | }
|
1622 | }
|
1623 |
|
1624 | return list;
|
1625 | }, []);
|
1626 | };
|
1627 |
|
1628 |
|
1629 |
|
1630 |
|
1631 |
|
1632 |
|
1633 |
|
1634 |
|
1635 |
|
1636 |
|
1637 |
|
1638 |
|
1639 |
|
1640 |
|
1641 |
|
1642 |
|
1643 |
|
1644 |
|
1645 |
|
1646 |
|
1647 | Document.prototype.isModified = function(paths, modifiedPaths) {
|
1648 | if (paths) {
|
1649 | if (!Array.isArray(paths)) {
|
1650 | paths = paths.split(' ');
|
1651 | }
|
1652 | const modified = modifiedPaths || this.modifiedPaths();
|
1653 | const directModifiedPaths = Object.keys(this.$__.activePaths.states.modify);
|
1654 | const isModifiedChild = paths.some(function(path) {
|
1655 | return !!~modified.indexOf(path);
|
1656 | });
|
1657 | return isModifiedChild || paths.some(function(path) {
|
1658 | return directModifiedPaths.some(function(mod) {
|
1659 | return mod === path || path.startsWith(mod + '.');
|
1660 | });
|
1661 | });
|
1662 | }
|
1663 | return this.$__.activePaths.some('modify');
|
1664 | };
|
1665 |
|
1666 |
|
1667 |
|
1668 |
|
1669 |
|
1670 |
|
1671 |
|
1672 |
|
1673 |
|
1674 |
|
1675 |
|
1676 |
|
1677 |
|
1678 |
|
1679 |
|
1680 |
|
1681 |
|
1682 |
|
1683 | Document.prototype.$isDefault = function(path) {
|
1684 | return (path in this.$__.activePaths.states.default);
|
1685 | };
|
1686 |
|
1687 |
|
1688 |
|
1689 |
|
1690 |
|
1691 |
|
1692 |
|
1693 |
|
1694 |
|
1695 |
|
1696 |
|
1697 |
|
1698 |
|
1699 |
|
1700 |
|
1701 |
|
1702 |
|
1703 |
|
1704 |
|
1705 |
|
1706 |
|
1707 |
|
1708 | Document.prototype.$isDeleted = function(val) {
|
1709 | if (arguments.length === 0) {
|
1710 | return !!this.$__.isDeleted;
|
1711 | }
|
1712 |
|
1713 | this.$__.isDeleted = !!val;
|
1714 | return this;
|
1715 | };
|
1716 |
|
1717 |
|
1718 |
|
1719 |
|
1720 |
|
1721 |
|
1722 |
|
1723 |
|
1724 |
|
1725 |
|
1726 |
|
1727 |
|
1728 |
|
1729 |
|
1730 |
|
1731 | Document.prototype.isDirectModified = function(path) {
|
1732 | return (path in this.$__.activePaths.states.modify);
|
1733 | };
|
1734 |
|
1735 |
|
1736 |
|
1737 |
|
1738 |
|
1739 |
|
1740 |
|
1741 |
|
1742 |
|
1743 | Document.prototype.isInit = function(path) {
|
1744 | return (path in this.$__.activePaths.states.init);
|
1745 | };
|
1746 |
|
1747 |
|
1748 |
|
1749 |
|
1750 |
|
1751 |
|
1752 |
|
1753 |
|
1754 |
|
1755 |
|
1756 |
|
1757 |
|
1758 |
|
1759 |
|
1760 |
|
1761 |
|
1762 | Document.prototype.isSelected = function isSelected(path) {
|
1763 | if (this.$__.selected) {
|
1764 | if (path === '_id') {
|
1765 | return this.$__.selected._id !== 0;
|
1766 | }
|
1767 |
|
1768 | const paths = Object.keys(this.$__.selected);
|
1769 | let i = paths.length;
|
1770 | let inclusive = null;
|
1771 | let cur;
|
1772 |
|
1773 | if (i === 1 && paths[0] === '_id') {
|
1774 |
|
1775 | return this.$__.selected._id === 0;
|
1776 | }
|
1777 |
|
1778 | while (i--) {
|
1779 | cur = paths[i];
|
1780 | if (cur === '_id') {
|
1781 | continue;
|
1782 | }
|
1783 | if (!isDefiningProjection(this.$__.selected[cur])) {
|
1784 | continue;
|
1785 | }
|
1786 | inclusive = !!this.$__.selected[cur];
|
1787 | break;
|
1788 | }
|
1789 |
|
1790 | if (inclusive === null) {
|
1791 | return true;
|
1792 | }
|
1793 |
|
1794 | if (path in this.$__.selected) {
|
1795 | return inclusive;
|
1796 | }
|
1797 |
|
1798 | i = paths.length;
|
1799 | const pathDot = path + '.';
|
1800 |
|
1801 | while (i--) {
|
1802 | cur = paths[i];
|
1803 | if (cur === '_id') {
|
1804 | continue;
|
1805 | }
|
1806 |
|
1807 | if (cur.startsWith(pathDot)) {
|
1808 | return inclusive || cur !== pathDot;
|
1809 | }
|
1810 |
|
1811 | if (pathDot.startsWith(cur + '.')) {
|
1812 | return inclusive;
|
1813 | }
|
1814 | }
|
1815 |
|
1816 | return !inclusive;
|
1817 | }
|
1818 |
|
1819 | return true;
|
1820 | };
|
1821 |
|
1822 |
|
1823 |
|
1824 |
|
1825 |
|
1826 |
|
1827 |
|
1828 |
|
1829 |
|
1830 |
|
1831 |
|
1832 |
|
1833 |
|
1834 |
|
1835 |
|
1836 |
|
1837 |
|
1838 |
|
1839 | Document.prototype.isDirectSelected = function isDirectSelected(path) {
|
1840 | if (this.$__.selected) {
|
1841 | if (path === '_id') {
|
1842 | return this.$__.selected._id !== 0;
|
1843 | }
|
1844 |
|
1845 | const paths = Object.keys(this.$__.selected);
|
1846 | let i = paths.length;
|
1847 | let inclusive = null;
|
1848 | let cur;
|
1849 |
|
1850 | if (i === 1 && paths[0] === '_id') {
|
1851 |
|
1852 | return this.$__.selected._id === 0;
|
1853 | }
|
1854 |
|
1855 | while (i--) {
|
1856 | cur = paths[i];
|
1857 | if (cur === '_id') {
|
1858 | continue;
|
1859 | }
|
1860 | if (!isDefiningProjection(this.$__.selected[cur])) {
|
1861 | continue;
|
1862 | }
|
1863 | inclusive = !!this.$__.selected[cur];
|
1864 | break;
|
1865 | }
|
1866 |
|
1867 | if (inclusive === null) {
|
1868 | return true;
|
1869 | }
|
1870 |
|
1871 | if (path in this.$__.selected) {
|
1872 | return inclusive;
|
1873 | }
|
1874 |
|
1875 | return !inclusive;
|
1876 | }
|
1877 |
|
1878 | return true;
|
1879 | };
|
1880 |
|
1881 |
|
1882 |
|
1883 |
|
1884 |
|
1885 |
|
1886 |
|
1887 |
|
1888 |
|
1889 |
|
1890 |
|
1891 |
|
1892 |
|
1893 |
|
1894 |
|
1895 |
|
1896 |
|
1897 |
|
1898 |
|
1899 |
|
1900 |
|
1901 | Document.prototype.validate = function(options, callback) {
|
1902 | if (typeof options === 'function') {
|
1903 | callback = options;
|
1904 | options = null;
|
1905 | }
|
1906 |
|
1907 | return utils.promiseOrCallback(callback, cb => this.$__validate(options, function(error) {
|
1908 | cb(error);
|
1909 | }), this.constructor.events);
|
1910 | };
|
1911 |
|
1912 |
|
1913 |
|
1914 |
|
1915 |
|
1916 | function _evaluateRequiredFunctions(doc) {
|
1917 | Object.keys(doc.$__.activePaths.states.require).forEach(path => {
|
1918 | const p = doc.schema.path(path);
|
1919 |
|
1920 | if (p != null && typeof p.originalRequiredValue === 'function') {
|
1921 | doc.$__.cachedRequired[path] = p.originalRequiredValue.call(doc);
|
1922 | }
|
1923 | });
|
1924 | }
|
1925 |
|
1926 |
|
1927 |
|
1928 |
|
1929 |
|
1930 | function _getPathsToValidate(doc) {
|
1931 | let i;
|
1932 | let len;
|
1933 | const skipSchemaValidators = {};
|
1934 |
|
1935 | _evaluateRequiredFunctions(doc);
|
1936 |
|
1937 |
|
1938 | let paths = Object.keys(doc.$__.activePaths.states.require).filter(function(path) {
|
1939 | if (!doc.isSelected(path) && !doc.isModified(path)) {
|
1940 | return false;
|
1941 | }
|
1942 | if (path in doc.$__.cachedRequired) {
|
1943 | return doc.$__.cachedRequired[path];
|
1944 | }
|
1945 | return true;
|
1946 | });
|
1947 |
|
1948 | paths = paths.concat(Object.keys(doc.$__.activePaths.states.init));
|
1949 | paths = paths.concat(Object.keys(doc.$__.activePaths.states.modify));
|
1950 | paths = paths.concat(Object.keys(doc.$__.activePaths.states.default));
|
1951 |
|
1952 | if (!doc.ownerDocument) {
|
1953 | const subdocs = doc.$__getAllSubdocs();
|
1954 | let subdoc;
|
1955 | len = subdocs.length;
|
1956 | const modifiedPaths = doc.modifiedPaths();
|
1957 | for (i = 0; i < len; ++i) {
|
1958 | subdoc = subdocs[i];
|
1959 | if (doc.isModified(subdoc.$basePath, modifiedPaths) &&
|
1960 | !doc.isDirectModified(subdoc.$basePath) &&
|
1961 | !doc.$isDefault(subdoc.$basePath)) {
|
1962 |
|
1963 |
|
1964 | paths = paths.filter(function(p) {
|
1965 | return p != null && p.indexOf(subdoc.$basePath + '.') !== 0;
|
1966 | });
|
1967 | paths.push(subdoc.$basePath);
|
1968 | skipSchemaValidators[subdoc.$basePath] = true;
|
1969 | }
|
1970 | }
|
1971 | }
|
1972 |
|
1973 |
|
1974 |
|
1975 | len = paths.length;
|
1976 | for (i = 0; i < len; ++i) {
|
1977 | const path = paths[i];
|
1978 |
|
1979 | const _pathType = doc.schema.path(path);
|
1980 | if (!_pathType ||
|
1981 | !_pathType.$isMongooseArray ||
|
1982 |
|
1983 |
|
1984 |
|
1985 | (_pathType.$isMongooseDocumentArray && !get(_pathType, 'schemaOptions.required'))) {
|
1986 | continue;
|
1987 | }
|
1988 |
|
1989 | const val = doc.$__getValue(path);
|
1990 | if (val) {
|
1991 | const numElements = val.length;
|
1992 | for (let j = 0; j < numElements; ++j) {
|
1993 | paths.push(path + '.' + j);
|
1994 | }
|
1995 | }
|
1996 | }
|
1997 |
|
1998 | const flattenOptions = { skipArrays: true };
|
1999 | len = paths.length;
|
2000 | for (i = 0; i < len; ++i) {
|
2001 | const pathToCheck = paths[i];
|
2002 | if (doc.schema.nested[pathToCheck]) {
|
2003 | let _v = doc.$__getValue(pathToCheck);
|
2004 | if (isMongooseObject(_v)) {
|
2005 | _v = _v.toObject({ transform: false });
|
2006 | }
|
2007 | const flat = flatten(_v, '', flattenOptions);
|
2008 | const _subpaths = Object.keys(flat).map(function(p) {
|
2009 | return pathToCheck + '.' + p;
|
2010 | });
|
2011 | paths = paths.concat(_subpaths);
|
2012 | }
|
2013 | }
|
2014 |
|
2015 | len = paths.length;
|
2016 | for (i = 0; i < len; ++i) {
|
2017 | const path = paths[i];
|
2018 | const _pathType = doc.schema.path(path);
|
2019 | if (!_pathType || !_pathType.$isSchemaMap) {
|
2020 | continue;
|
2021 | }
|
2022 |
|
2023 | const val = doc.$__getValue(path);
|
2024 | if (val == null) {
|
2025 | continue;
|
2026 | }
|
2027 | for (const key of val.keys()) {
|
2028 | paths.push(path + '.' + key);
|
2029 | }
|
2030 | }
|
2031 |
|
2032 | return [paths, skipSchemaValidators];
|
2033 | }
|
2034 |
|
2035 |
|
2036 |
|
2037 |
|
2038 |
|
2039 | Document.prototype.$__validate = function(options, callback) {
|
2040 | if (typeof options === 'function') {
|
2041 | callback = options;
|
2042 | options = null;
|
2043 | }
|
2044 |
|
2045 | const hasValidateModifiedOnlyOption = options &&
|
2046 | (typeof options === 'object') &&
|
2047 | ('validateModifiedOnly' in options);
|
2048 |
|
2049 | let shouldValidateModifiedOnly;
|
2050 | if (hasValidateModifiedOnlyOption) {
|
2051 | shouldValidateModifiedOnly = !!options.validateModifiedOnly;
|
2052 | } else {
|
2053 | shouldValidateModifiedOnly = this.schema.options.validateModifiedOnly;
|
2054 | }
|
2055 |
|
2056 | const _this = this;
|
2057 | const _complete = () => {
|
2058 | const err = this.$__.validationError;
|
2059 | this.$__.validationError = undefined;
|
2060 | this.$__.cachedRequired = {};
|
2061 | this.emit('validate', _this);
|
2062 | this.constructor.emit('validate', _this);
|
2063 | if (err) {
|
2064 | for (const key in err.errors) {
|
2065 |
|
2066 | if (!this[documentArrayParent] && err.errors[key] instanceof MongooseError.CastError) {
|
2067 | this.invalidate(key, err.errors[key]);
|
2068 | }
|
2069 | }
|
2070 |
|
2071 | return err;
|
2072 | }
|
2073 | };
|
2074 |
|
2075 |
|
2076 | const pathDetails = _getPathsToValidate(this);
|
2077 | const paths = shouldValidateModifiedOnly ?
|
2078 | pathDetails[0].filter((path) => this.isModified(path)) :
|
2079 | pathDetails[0];
|
2080 | const skipSchemaValidators = pathDetails[1];
|
2081 |
|
2082 | if (paths.length === 0) {
|
2083 | return process.nextTick(function() {
|
2084 | const error = _complete();
|
2085 | if (error) {
|
2086 | return _this.schema.s.hooks.execPost('validate:error', _this, [ _this], { error: error }, function(error) {
|
2087 | callback(error);
|
2088 | });
|
2089 | }
|
2090 | callback(null, _this);
|
2091 | });
|
2092 | }
|
2093 |
|
2094 | const validated = {};
|
2095 | let total = 0;
|
2096 |
|
2097 | const complete = function() {
|
2098 | const error = _complete();
|
2099 | if (error) {
|
2100 | return _this.schema.s.hooks.execPost('validate:error', _this, [ _this], { error: error }, function(error) {
|
2101 | callback(error);
|
2102 | });
|
2103 | }
|
2104 | callback(null, _this);
|
2105 | };
|
2106 |
|
2107 | const validatePath = function(path) {
|
2108 | if (path == null || validated[path]) {
|
2109 | return;
|
2110 | }
|
2111 |
|
2112 | validated[path] = true;
|
2113 | total++;
|
2114 |
|
2115 | process.nextTick(function() {
|
2116 | const p = _this.schema.path(path);
|
2117 |
|
2118 | if (!p) {
|
2119 | return --total || complete();
|
2120 | }
|
2121 |
|
2122 |
|
2123 | if (!_this.$isValid(path)) {
|
2124 | --total || complete();
|
2125 | return;
|
2126 | }
|
2127 |
|
2128 | const val = _this.$__getValue(path);
|
2129 | const scope = path in _this.$__.pathsToScopes ?
|
2130 | _this.$__.pathsToScopes[path] :
|
2131 | _this;
|
2132 |
|
2133 | p.doValidate(val, function(err) {
|
2134 | if (err && (!p.$isMongooseDocumentArray || err.$isArrayValidatorError)) {
|
2135 | if (p.$isSingleNested &&
|
2136 | err.name === 'ValidationError' &&
|
2137 | p.schema.options.storeSubdocValidationError === false) {
|
2138 | return --total || complete();
|
2139 | }
|
2140 | _this.invalidate(path, err, undefined, true);
|
2141 | }
|
2142 | --total || complete();
|
2143 | }, scope, { skipSchemaValidators: skipSchemaValidators[path], path: path });
|
2144 | });
|
2145 | };
|
2146 |
|
2147 | const numPaths = paths.length;
|
2148 | for (let i = 0; i < numPaths; ++i) {
|
2149 | validatePath(paths[i]);
|
2150 | }
|
2151 | };
|
2152 |
|
2153 |
|
2154 |
|
2155 |
|
2156 |
|
2157 |
|
2158 |
|
2159 |
|
2160 |
|
2161 |
|
2162 |
|
2163 |
|
2164 |
|
2165 |
|
2166 |
|
2167 |
|
2168 |
|
2169 |
|
2170 |
|
2171 |
|
2172 |
|
2173 |
|
2174 | Document.prototype.validateSync = function(pathsToValidate, options) {
|
2175 | const _this = this;
|
2176 |
|
2177 | const hasValidateModifiedOnlyOption = options &&
|
2178 | (typeof options === 'object') &&
|
2179 | ('validateModifiedOnly' in options);
|
2180 |
|
2181 | let shouldValidateModifiedOnly;
|
2182 | if (hasValidateModifiedOnlyOption) {
|
2183 | shouldValidateModifiedOnly = !!options.validateModifiedOnly;
|
2184 | } else {
|
2185 | shouldValidateModifiedOnly = this.schema.options.validateModifiedOnly;
|
2186 | }
|
2187 |
|
2188 | if (typeof pathsToValidate === 'string') {
|
2189 | pathsToValidate = pathsToValidate.split(' ');
|
2190 | }
|
2191 |
|
2192 |
|
2193 | const pathDetails = _getPathsToValidate(this);
|
2194 | let paths = shouldValidateModifiedOnly ?
|
2195 | pathDetails[0].filter((path) => this.isModified(path)) :
|
2196 | pathDetails[0];
|
2197 | const skipSchemaValidators = pathDetails[1];
|
2198 |
|
2199 | if (pathsToValidate && pathsToValidate.length) {
|
2200 | const tmp = [];
|
2201 | for (let i = 0; i < paths.length; ++i) {
|
2202 | if (pathsToValidate.indexOf(paths[i]) !== -1) {
|
2203 | tmp.push(paths[i]);
|
2204 | }
|
2205 | }
|
2206 | paths = tmp;
|
2207 | }
|
2208 |
|
2209 | const validating = {};
|
2210 |
|
2211 | paths.forEach(function(path) {
|
2212 | if (validating[path]) {
|
2213 | return;
|
2214 | }
|
2215 |
|
2216 | validating[path] = true;
|
2217 |
|
2218 | const p = _this.schema.path(path);
|
2219 | if (!p) {
|
2220 | return;
|
2221 | }
|
2222 | if (!_this.$isValid(path)) {
|
2223 | return;
|
2224 | }
|
2225 |
|
2226 | const val = _this.$__getValue(path);
|
2227 | const err = p.doValidateSync(val, _this, {
|
2228 | skipSchemaValidators: skipSchemaValidators[path],
|
2229 | path: path
|
2230 | });
|
2231 | if (err && (!p.$isMongooseDocumentArray || err.$isArrayValidatorError)) {
|
2232 | if (p.$isSingleNested &&
|
2233 | err.name === 'ValidationError' &&
|
2234 | p.schema.options.storeSubdocValidationError === false) {
|
2235 | return;
|
2236 | }
|
2237 | _this.invalidate(path, err, undefined, true);
|
2238 | }
|
2239 | });
|
2240 |
|
2241 | const err = _this.$__.validationError;
|
2242 | _this.$__.validationError = undefined;
|
2243 | _this.emit('validate', _this);
|
2244 | _this.constructor.emit('validate', _this);
|
2245 |
|
2246 | if (err) {
|
2247 | for (const key in err.errors) {
|
2248 |
|
2249 | if (err.errors[key] instanceof MongooseError.CastError) {
|
2250 | _this.invalidate(key, err.errors[key]);
|
2251 | }
|
2252 | }
|
2253 | }
|
2254 |
|
2255 | return err;
|
2256 | };
|
2257 |
|
2258 |
|
2259 |
|
2260 |
|
2261 |
|
2262 |
|
2263 |
|
2264 |
|
2265 |
|
2266 |
|
2267 |
|
2268 |
|
2269 |
|
2270 |
|
2271 |
|
2272 |
|
2273 |
|
2274 |
|
2275 |
|
2276 |
|
2277 |
|
2278 |
|
2279 |
|
2280 |
|
2281 |
|
2282 |
|
2283 |
|
2284 |
|
2285 |
|
2286 |
|
2287 |
|
2288 |
|
2289 | Document.prototype.invalidate = function(path, err, val, kind) {
|
2290 | if (!this.$__.validationError) {
|
2291 | this.$__.validationError = new ValidationError(this);
|
2292 | }
|
2293 |
|
2294 | if (this.$__.validationError.errors[path]) {
|
2295 | return;
|
2296 | }
|
2297 |
|
2298 | if (!err || typeof err === 'string') {
|
2299 | err = new ValidatorError({
|
2300 | path: path,
|
2301 | message: err,
|
2302 | type: kind || 'user defined',
|
2303 | value: val
|
2304 | });
|
2305 | }
|
2306 |
|
2307 | if (this.$__.validationError === err) {
|
2308 | return this.$__.validationError;
|
2309 | }
|
2310 |
|
2311 | this.$__.validationError.addError(path, err);
|
2312 | return this.$__.validationError;
|
2313 | };
|
2314 |
|
2315 |
|
2316 |
|
2317 |
|
2318 |
|
2319 |
|
2320 |
|
2321 |
|
2322 |
|
2323 |
|
2324 |
|
2325 | Document.prototype.$markValid = function(path) {
|
2326 | if (!this.$__.validationError || !this.$__.validationError.errors[path]) {
|
2327 | return;
|
2328 | }
|
2329 |
|
2330 | delete this.$__.validationError.errors[path];
|
2331 | if (Object.keys(this.$__.validationError.errors).length === 0) {
|
2332 | this.$__.validationError = null;
|
2333 | }
|
2334 | };
|
2335 |
|
2336 |
|
2337 |
|
2338 |
|
2339 |
|
2340 |
|
2341 |
|
2342 |
|
2343 |
|
2344 |
|
2345 |
|
2346 |
|
2347 |
|
2348 |
|
2349 |
|
2350 |
|
2351 |
|
2352 |
|
2353 |
|
2354 |
|
2355 |
|
2356 |
|
2357 |
|
2358 |
|
2359 |
|
2360 |
|
2361 |
|
2362 |
|
2363 |
|
2364 |
|
2365 |
|
2366 |
|
2367 |
|
2368 |
|
2369 |
|
2370 |
|
2371 |
|
2372 |
|
2373 |
|
2374 |
|
2375 |
|
2376 |
|
2377 |
|
2378 |
|
2379 | Document.prototype.$isValid = function(path) {
|
2380 | return !this.$__.validationError || !this.$__.validationError.errors[path];
|
2381 | };
|
2382 |
|
2383 |
|
2384 |
|
2385 |
|
2386 |
|
2387 |
|
2388 |
|
2389 |
|
2390 |
|
2391 |
|
2392 |
|
2393 | Document.prototype.$__reset = function reset() {
|
2394 | let _this = this;
|
2395 | DocumentArray || (DocumentArray = require('./types/documentarray'));
|
2396 |
|
2397 | this.$__.activePaths
|
2398 | .map('init', 'modify', function(i) {
|
2399 | return _this.$__getValue(i);
|
2400 | })
|
2401 | .filter(function(val) {
|
2402 | return val && val instanceof Array && val.isMongooseDocumentArray && val.length;
|
2403 | })
|
2404 | .forEach(function(array) {
|
2405 | let i = array.length;
|
2406 | while (i--) {
|
2407 | const doc = array[i];
|
2408 | if (!doc) {
|
2409 | continue;
|
2410 | }
|
2411 | doc.$__reset();
|
2412 | }
|
2413 |
|
2414 | _this.$__.activePaths.init(array.$path());
|
2415 |
|
2416 | array[arrayAtomicsSymbol] = {};
|
2417 | });
|
2418 |
|
2419 | this.$__.activePaths.
|
2420 | map('init', 'modify', function(i) {
|
2421 | return _this.$__getValue(i);
|
2422 | }).
|
2423 | filter(function(val) {
|
2424 | return val && val.$isSingleNested;
|
2425 | }).
|
2426 | forEach(function(doc) {
|
2427 | doc.$__reset();
|
2428 | _this.$__.activePaths.init(doc.$basePath);
|
2429 | });
|
2430 |
|
2431 |
|
2432 | this.$__dirty().forEach(function(dirt) {
|
2433 | const type = dirt.value;
|
2434 |
|
2435 | if (type && type[arrayAtomicsSymbol]) {
|
2436 | type[arrayAtomicsSymbol] = {};
|
2437 | }
|
2438 | });
|
2439 |
|
2440 |
|
2441 | this.$__.activePaths.clear('modify');
|
2442 | this.$__.activePaths.clear('default');
|
2443 | this.$__.validationError = undefined;
|
2444 | this.errors = undefined;
|
2445 | _this = this;
|
2446 | this.schema.requiredPaths().forEach(function(path) {
|
2447 | _this.$__.activePaths.require(path);
|
2448 | });
|
2449 |
|
2450 | return this;
|
2451 | };
|
2452 |
|
2453 |
|
2454 |
|
2455 |
|
2456 |
|
2457 |
|
2458 |
|
2459 |
|
2460 |
|
2461 |
|
2462 | Document.prototype.$__dirty = function() {
|
2463 | const _this = this;
|
2464 |
|
2465 | let all = this.$__.activePaths.map('modify', function(path) {
|
2466 | return {
|
2467 | path: path,
|
2468 | value: _this.$__getValue(path),
|
2469 | schema: _this.$__path(path)
|
2470 | };
|
2471 | });
|
2472 |
|
2473 |
|
2474 |
|
2475 | all = all.concat(this.$__.activePaths.map('default', function(path) {
|
2476 | if (path === '_id' || _this.$__getValue(path) == null) {
|
2477 | return;
|
2478 | }
|
2479 | return {
|
2480 | path: path,
|
2481 | value: _this.$__getValue(path),
|
2482 | schema: _this.$__path(path)
|
2483 | };
|
2484 | }));
|
2485 |
|
2486 |
|
2487 | all.sort(function(a, b) {
|
2488 | return (a.path < b.path ? -1 : (a.path > b.path ? 1 : 0));
|
2489 | });
|
2490 |
|
2491 |
|
2492 | const minimal = [];
|
2493 | let lastPath;
|
2494 | let top;
|
2495 |
|
2496 | all.forEach(function(item) {
|
2497 | if (!item) {
|
2498 | return;
|
2499 | }
|
2500 | if (lastPath == null || item.path.indexOf(lastPath) !== 0) {
|
2501 | lastPath = item.path + '.';
|
2502 | minimal.push(item);
|
2503 | top = item;
|
2504 | } else if (top != null &&
|
2505 | top.value != null &&
|
2506 | top.value[arrayAtomicsSymbol] != null &&
|
2507 | top.value.hasAtomics()) {
|
2508 |
|
2509 |
|
2510 |
|
2511 |
|
2512 | top.value[arrayAtomicsSymbol] = {};
|
2513 | top.value[arrayAtomicsSymbol].$set = top.value;
|
2514 | }
|
2515 | });
|
2516 |
|
2517 | top = lastPath = null;
|
2518 | return minimal;
|
2519 | };
|
2520 |
|
2521 | /**
|
2522 | * Assigns/compiles `schema` into this documents prototype.
|
2523 | *
|
2524 | * @param {Schema} schema
|
2525 | * @api private
|
2526 | * @method $__setSchema
|
2527 | * @memberOf Document
|
2528 | * @instance
|
2529 | */
|
2530 |
|
2531 | Document.prototype.$__setSchema = function(schema) {
|
2532 | schema.plugin(idGetter, { deduplicate: true });
|
2533 | compile(schema.tree, this, undefined, schema.options);
|
2534 |
|
2535 |
|
2536 | for (const key of Object.keys(schema.virtuals)) {
|
2537 | schema.virtuals[key]._applyDefaultGetters();
|
2538 | }
|
2539 |
|
2540 | this.schema = schema;
|
2541 | this[documentSchemaSymbol] = schema;
|
2542 | };
|
2543 |
|
2544 |
|
2545 |
|
2546 |
|
2547 |
|
2548 |
|
2549 |
|
2550 |
|
2551 |
|
2552 |
|
2553 |
|
2554 | Document.prototype.$__getArrayPathsToValidate = function() {
|
2555 | DocumentArray || (DocumentArray = require('./types/documentarray'));
|
2556 |
|
2557 |
|
2558 | return this.$__.activePaths
|
2559 | .map('init', 'modify', function(i) {
|
2560 | return this.$__getValue(i);
|
2561 | }.bind(this))
|
2562 | .filter(function(val) {
|
2563 | return val && val instanceof Array && val.isMongooseDocumentArray && val.length;
|
2564 | }).reduce(function(seed, array) {
|
2565 | return seed.concat(array);
|
2566 | }, [])
|
2567 | .filter(function(doc) {
|
2568 | return doc;
|
2569 | });
|
2570 | };
|
2571 |
|
2572 |
|
2573 |
|
2574 |
|
2575 |
|
2576 |
|
2577 |
|
2578 |
|
2579 |
|
2580 |
|
2581 |
|
2582 | Document.prototype.$__getAllSubdocs = function() {
|
2583 | DocumentArray || (DocumentArray = require('./types/documentarray'));
|
2584 | Embedded = Embedded || require('./types/embedded');
|
2585 |
|
2586 | function docReducer(doc, seed, path) {
|
2587 | let val = doc;
|
2588 | if (path) {
|
2589 | if (doc instanceof Document && doc[documentSchemaSymbol].paths[path]) {
|
2590 | val = doc._doc[path];
|
2591 | } else {
|
2592 | val = doc[path];
|
2593 | }
|
2594 | }
|
2595 | if (val instanceof Embedded) {
|
2596 | seed.push(val);
|
2597 | } else if (val instanceof Map) {
|
2598 | seed = Array.from(val.keys()).reduce(function(seed, path) {
|
2599 | return docReducer(val.get(path), seed, null);
|
2600 | }, seed);
|
2601 | } else if (val && val.$isSingleNested) {
|
2602 | seed = Object.keys(val._doc).reduce(function(seed, path) {
|
2603 | return docReducer(val._doc, seed, path);
|
2604 | }, seed);
|
2605 | seed.push(val);
|
2606 | } else if (val && val.isMongooseDocumentArray) {
|
2607 | val.forEach(function _docReduce(doc) {
|
2608 | if (!doc || !doc._doc) {
|
2609 | return;
|
2610 | }
|
2611 | seed = Object.keys(doc._doc).reduce(function(seed, path) {
|
2612 | return docReducer(doc._doc, seed, path);
|
2613 | }, seed);
|
2614 | if (doc instanceof Embedded) {
|
2615 | seed.push(doc);
|
2616 | }
|
2617 | });
|
2618 | } else if (val instanceof Document && val.$__isNested) {
|
2619 | seed = Object.keys(val).reduce(function(seed, path) {
|
2620 | return docReducer(val, seed, path);
|
2621 | }, seed);
|
2622 | }
|
2623 | return seed;
|
2624 | }
|
2625 |
|
2626 | const _this = this;
|
2627 | const subDocs = Object.keys(this._doc).reduce(function(seed, path) {
|
2628 | return docReducer(_this, seed, path);
|
2629 | }, []);
|
2630 |
|
2631 | return subDocs;
|
2632 | };
|
2633 |
|
2634 |
|
2635 |
|
2636 |
|
2637 |
|
2638 | function applyQueue(doc) {
|
2639 | const q = doc.schema && doc.schema.callQueue;
|
2640 | if (!q.length) {
|
2641 | return;
|
2642 | }
|
2643 | let pair;
|
2644 |
|
2645 | for (let i = 0; i < q.length; ++i) {
|
2646 | pair = q[i];
|
2647 | if (pair[0] !== 'pre' && pair[0] !== 'post' && pair[0] !== 'on') {
|
2648 | doc[pair[0]].apply(doc, pair[1]);
|
2649 | }
|
2650 | }
|
2651 | }
|
2652 |
|
2653 |
|
2654 |
|
2655 |
|
2656 |
|
2657 | Document.prototype.$__handleReject = function handleReject(err) {
|
2658 |
|
2659 | if (this.listeners('error').length) {
|
2660 | this.emit('error', err);
|
2661 | } else if (this.constructor.listeners && this.constructor.listeners('error').length) {
|
2662 | this.constructor.emit('error', err);
|
2663 | } else if (this.listeners && this.listeners('error').length) {
|
2664 | this.emit('error', err);
|
2665 | }
|
2666 | };
|
2667 |
|
2668 |
|
2669 |
|
2670 |
|
2671 |
|
2672 |
|
2673 |
|
2674 |
|
2675 |
|
2676 |
|
2677 | Document.prototype.$toObject = function(options, json) {
|
2678 | let defaultOptions = {
|
2679 | transform: true,
|
2680 | flattenDecimals: true
|
2681 | };
|
2682 |
|
2683 | const path = json ? 'toJSON' : 'toObject';
|
2684 | const baseOptions = get(this, 'constructor.base.options.' + path, {});
|
2685 | const schemaOptions = get(this, 'schema.options', {});
|
2686 |
|
2687 |
|
2688 | defaultOptions = utils.options(defaultOptions, clone(baseOptions));
|
2689 | defaultOptions = utils.options(defaultOptions, clone(schemaOptions[path] || {}));
|
2690 |
|
2691 |
|
2692 | options = utils.isPOJO(options) ? clone(options) : {};
|
2693 |
|
2694 | if (!('flattenMaps' in options)) {
|
2695 | options.flattenMaps = defaultOptions.flattenMaps;
|
2696 | }
|
2697 |
|
2698 | let _minimize;
|
2699 | if (options.minimize != null) {
|
2700 | _minimize = options.minimize;
|
2701 | } else if (defaultOptions.minimize != null) {
|
2702 | _minimize = defaultOptions.minimize;
|
2703 | } else {
|
2704 | _minimize = schemaOptions.minimize;
|
2705 | }
|
2706 |
|
2707 |
|
2708 |
|
2709 |
|
2710 |
|
2711 | const cloneOptions = Object.assign(utils.clone(options), {
|
2712 | _isNested: true,
|
2713 | json: json,
|
2714 | minimize: _minimize
|
2715 | });
|
2716 |
|
2717 | const depopulate = options.depopulate ||
|
2718 | get(options, '_parentOptions.depopulate', false);
|
2719 | // _isNested will only be true if this is not the top level document, we
|
2720 | // should never depopulate
|
2721 | if (depopulate && options._isNested && this.$__.wasPopulated) {
|
2722 |
|
2723 | return clone(this._id, cloneOptions);
|
2724 | }
|
2725 |
|
2726 |
|
2727 | options = utils.options(defaultOptions, options);
|
2728 | options._isNested = true;
|
2729 | options.json = json;
|
2730 | options.minimize = _minimize;
|
2731 |
|
2732 | cloneOptions._parentOptions = options;
|
2733 |
|
2734 |
|
2735 |
|
2736 | const originalTransform = options.transform;
|
2737 |
|
2738 | let ret = clone(this._doc, cloneOptions) || {};
|
2739 |
|
2740 | if (options.getters) {
|
2741 | applyGetters(this, ret, 'paths', cloneOptions);
|
2742 |
|
2743 |
|
2744 | if (options.minimize) {
|
2745 | ret = minimize(ret) || {};
|
2746 | }
|
2747 | }
|
2748 |
|
2749 | if (options.virtuals || options.getters && options.virtuals !== false) {
|
2750 | applyGetters(this, ret, 'virtuals', cloneOptions);
|
2751 | }
|
2752 |
|
2753 | if (options.versionKey === false && this.schema.options.versionKey) {
|
2754 | delete ret[this.schema.options.versionKey];
|
2755 | }
|
2756 |
|
2757 | let transform = options.transform;
|
2758 |
|
2759 |
|
2760 |
|
2761 |
|
2762 |
|
2763 |
|
2764 | if (transform === true || (schemaOptions.toObject && transform)) {
|
2765 | const opts = options.json ? schemaOptions.toJSON : schemaOptions.toObject;
|
2766 |
|
2767 | if (opts) {
|
2768 | transform = (typeof options.transform === 'function' ? options.transform : opts.transform);
|
2769 | }
|
2770 | } else {
|
2771 | options.transform = originalTransform;
|
2772 | }
|
2773 |
|
2774 | if (typeof transform === 'function') {
|
2775 | const xformed = transform(this, ret, options);
|
2776 | if (typeof xformed !== 'undefined') {
|
2777 | ret = xformed;
|
2778 | }
|
2779 | }
|
2780 |
|
2781 | return ret;
|
2782 | };
|
2783 |
|
2784 |
|
2785 |
|
2786 |
|
2787 |
|
2788 |
|
2789 |
|
2790 |
|
2791 |
|
2792 |
|
2793 |
|
2794 |
|
2795 |
|
2796 |
|
2797 |
|
2798 |
|
2799 |
|
2800 |
|
2801 |
|
2802 |
|
2803 |
|
2804 |
|
2805 |
|
2806 |
|
2807 |
|
2808 |
|
2809 |
|
2810 |
|
2811 |
|
2812 |
|
2813 |
|
2814 |
|
2815 |
|
2816 |
|
2817 |
|
2818 |
|
2819 |
|
2820 |
|
2821 |
|
2822 |
|
2823 |
|
2824 |
|
2825 |
|
2826 |
|
2827 |
|
2828 |
|
2829 |
|
2830 |
|
2831 |
|
2832 |
|
2833 |
|
2834 |
|
2835 |
|
2836 |
|
2837 |
|
2838 |
|
2839 |
|
2840 |
|
2841 |
|
2842 |
|
2843 |
|
2844 |
|
2845 |
|
2846 |
|
2847 |
|
2848 |
|
2849 |
|
2850 |
|
2851 |
|
2852 |
|
2853 |
|
2854 |
|
2855 |
|
2856 |
|
2857 |
|
2858 |
|
2859 |
|
2860 |
|
2861 |
|
2862 |
|
2863 |
|
2864 |
|
2865 |
|
2866 |
|
2867 |
|
2868 |
|
2869 |
|
2870 |
|
2871 |
|
2872 |
|
2873 |
|
2874 |
|
2875 |
|
2876 |
|
2877 |
|
2878 |
|
2879 |
|
2880 |
|
2881 |
|
2882 |
|
2883 |
|
2884 |
|
2885 |
|
2886 |
|
2887 |
|
2888 |
|
2889 |
|
2890 |
|
2891 |
|
2892 |
|
2893 |
|
2894 |
|
2895 |
|
2896 |
|
2897 |
|
2898 |
|
2899 |
|
2900 |
|
2901 |
|
2902 |
|
2903 |
|
2904 |
|
2905 |
|
2906 |
|
2907 |
|
2908 |
|
2909 | Document.prototype.toObject = function(options) {
|
2910 | return this.$toObject(options);
|
2911 | };
|
2912 |
|
2913 |
|
2914 |
|
2915 |
|
2916 |
|
2917 |
|
2918 |
|
2919 |
|
2920 | function minimize(obj) {
|
2921 | const keys = Object.keys(obj);
|
2922 | let i = keys.length;
|
2923 | let hasKeys;
|
2924 | let key;
|
2925 | let val;
|
2926 |
|
2927 | while (i--) {
|
2928 | key = keys[i];
|
2929 | val = obj[key];
|
2930 |
|
2931 | if (utils.isObject(val) && !Buffer.isBuffer(val)) {
|
2932 | obj[key] = minimize(val);
|
2933 | }
|
2934 |
|
2935 | if (undefined === obj[key]) {
|
2936 | delete obj[key];
|
2937 | continue;
|
2938 | }
|
2939 |
|
2940 | hasKeys = true;
|
2941 | }
|
2942 |
|
2943 | return hasKeys
|
2944 | ? obj
|
2945 | : undefined;
|
2946 | }
|
2947 |
|
2948 |
|
2949 |
|
2950 |
|
2951 |
|
2952 |
|
2953 |
|
2954 |
|
2955 |
|
2956 |
|
2957 | function applyGetters(self, json, type, options) {
|
2958 | const schema = self.schema;
|
2959 | const paths = Object.keys(schema[type]);
|
2960 | let i = paths.length;
|
2961 | const numPaths = i;
|
2962 | let path;
|
2963 | let assignPath;
|
2964 | let cur = self._doc;
|
2965 | let v;
|
2966 |
|
2967 | if (!cur) {
|
2968 | return json;
|
2969 | }
|
2970 |
|
2971 | if (type === 'virtuals') {
|
2972 | options = options || {};
|
2973 | for (i = 0; i < numPaths; ++i) {
|
2974 | path = paths[i];
|
2975 |
|
2976 |
|
2977 |
|
2978 | assignPath = path;
|
2979 | if (options.path != null) {
|
2980 | if (!path.startsWith(options.path + '.')) {
|
2981 | continue;
|
2982 | }
|
2983 | assignPath = path.substr(options.path.length + 1);
|
2984 | }
|
2985 | const parts = assignPath.split('.');
|
2986 | v = clone(self.get(path), options);
|
2987 | if (v === void 0) {
|
2988 | continue;
|
2989 | }
|
2990 | const plen = parts.length;
|
2991 | cur = json;
|
2992 | for (let j = 0; j < plen - 1; ++j) {
|
2993 | cur[parts[j]] = cur[parts[j]] || {};
|
2994 | cur = cur[parts[j]];
|
2995 | }
|
2996 | cur[parts[plen - 1]] = v;
|
2997 | }
|
2998 |
|
2999 | return json;
|
3000 | }
|
3001 |
|
3002 | while (i--) {
|
3003 | path = paths[i];
|
3004 |
|
3005 | const parts = path.split('.');
|
3006 | const plen = parts.length;
|
3007 | const last = plen - 1;
|
3008 | let branch = json;
|
3009 | let part;
|
3010 | cur = self._doc;
|
3011 |
|
3012 | if (!self.isSelected(path)) {
|
3013 | continue;
|
3014 | }
|
3015 |
|
3016 | for (let ii = 0; ii < plen; ++ii) {
|
3017 | part = parts[ii];
|
3018 | v = cur[part];
|
3019 | if (ii === last) {
|
3020 | const val = self.get(path);
|
3021 |
|
3022 |
|
3023 |
|
3024 | if (val != null && val.$__ == null) {
|
3025 | branch[part] = clone(val, options);
|
3026 | }
|
3027 | } else if (v == null) {
|
3028 | if (part in cur) {
|
3029 | branch[part] = v;
|
3030 | }
|
3031 | break;
|
3032 | } else {
|
3033 | branch = branch[part] || (branch[part] = {});
|
3034 | }
|
3035 | cur = v;
|
3036 | }
|
3037 | }
|
3038 |
|
3039 | return json;
|
3040 | }
|
3041 |
|
3042 |
|
3043 |
|
3044 |
|
3045 |
|
3046 |
|
3047 |
|
3048 |
|
3049 |
|
3050 |
|
3051 |
|
3052 |
|
3053 |
|
3054 |
|
3055 |
|
3056 |
|
3057 |
|
3058 |
|
3059 |
|
3060 | Document.prototype.toJSON = function(options) {
|
3061 | return this.$toObject(options, true);
|
3062 | };
|
3063 |
|
3064 |
|
3065 |
|
3066 |
|
3067 |
|
3068 |
|
3069 |
|
3070 |
|
3071 |
|
3072 |
|
3073 | Document.prototype.inspect = function(options) {
|
3074 | const isPOJO = utils.isPOJO(options);
|
3075 | let opts;
|
3076 | if (isPOJO) {
|
3077 | opts = options;
|
3078 | opts.minimize = false;
|
3079 | }
|
3080 | return this.toObject(opts);
|
3081 | };
|
3082 |
|
3083 | if (inspect.custom) {
|
3084 | |
3085 |
|
3086 |
|
3087 |
|
3088 | Document.prototype[inspect.custom] = Document.prototype.inspect;
|
3089 | }
|
3090 |
|
3091 |
|
3092 |
|
3093 |
|
3094 |
|
3095 |
|
3096 |
|
3097 |
|
3098 |
|
3099 |
|
3100 | Document.prototype.toString = function() {
|
3101 | return inspect(this.inspect());
|
3102 | };
|
3103 |
|
3104 |
|
3105 |
|
3106 |
|
3107 |
|
3108 |
|
3109 |
|
3110 |
|
3111 |
|
3112 |
|
3113 |
|
3114 |
|
3115 |
|
3116 |
|
3117 |
|
3118 | Document.prototype.equals = function(doc) {
|
3119 | if (!doc) {
|
3120 | return false;
|
3121 | }
|
3122 |
|
3123 | const tid = this.get('_id');
|
3124 | const docid = doc.get ? doc.get('_id') : doc;
|
3125 | if (!tid && !docid) {
|
3126 | return deepEqual(this, doc);
|
3127 | }
|
3128 | return tid && tid.equals
|
3129 | ? tid.equals(docid)
|
3130 | : tid === docid;
|
3131 | };
|
3132 |
|
3133 |
|
3134 |
|
3135 |
|
3136 |
|
3137 |
|
3138 |
|
3139 |
|
3140 |
|
3141 |
|
3142 |
|
3143 |
|
3144 |
|
3145 |
|
3146 |
|
3147 |
|
3148 |
|
3149 |
|
3150 |
|
3151 |
|
3152 |
|
3153 |
|
3154 |
|
3155 |
|
3156 |
|
3157 |
|
3158 |
|
3159 |
|
3160 |
|
3161 |
|
3162 |
|
3163 |
|
3164 |
|
3165 |
|
3166 |
|
3167 |
|
3168 |
|
3169 |
|
3170 |
|
3171 |
|
3172 |
|
3173 |
|
3174 |
|
3175 |
|
3176 |
|
3177 |
|
3178 | Document.prototype.populate = function populate() {
|
3179 | if (arguments.length === 0) {
|
3180 | return this;
|
3181 | }
|
3182 |
|
3183 | const pop = this.$__.populate || (this.$__.populate = {});
|
3184 | const args = utils.args(arguments);
|
3185 | let fn;
|
3186 |
|
3187 | if (typeof args[args.length - 1] === 'function') {
|
3188 | fn = args.pop();
|
3189 | }
|
3190 |
|
3191 |
|
3192 | if (args.length) {
|
3193 |
|
3194 | const res = utils.populate.apply(null, args);
|
3195 | for (let i = 0; i < res.length; ++i) {
|
3196 | pop[res[i].path] = res[i];
|
3197 | }
|
3198 | }
|
3199 |
|
3200 | if (fn) {
|
3201 | const paths = utils.object.vals(pop);
|
3202 | this.$__.populate = undefined;
|
3203 | let topLevelModel = this.constructor;
|
3204 | if (this.$__isNested) {
|
3205 | topLevelModel = this.$__.scope.constructor;
|
3206 | const nestedPath = this.$__.nestedPath;
|
3207 | paths.forEach(function(populateOptions) {
|
3208 | populateOptions.path = nestedPath + '.' + populateOptions.path;
|
3209 | });
|
3210 | }
|
3211 |
|
3212 |
|
3213 |
|
3214 | if (this.$session() != null) {
|
3215 | const session = this.$session();
|
3216 | paths.forEach(path => {
|
3217 | if (path.options == null) {
|
3218 | path.options = { session: session };
|
3219 | return;
|
3220 | }
|
3221 | if (!('session' in path.options)) {
|
3222 | path.options.session = session;
|
3223 | }
|
3224 | });
|
3225 | }
|
3226 |
|
3227 | topLevelModel.populate(this, paths, fn);
|
3228 | }
|
3229 |
|
3230 | return this;
|
3231 | };
|
3232 |
|
3233 |
|
3234 |
|
3235 |
|
3236 |
|
3237 |
|
3238 |
|
3239 |
|
3240 |
|
3241 |
|
3242 |
|
3243 |
|
3244 |
|
3245 |
|
3246 |
|
3247 |
|
3248 |
|
3249 |
|
3250 |
|
3251 |
|
3252 |
|
3253 |
|
3254 |
|
3255 |
|
3256 |
|
3257 |
|
3258 |
|
3259 |
|
3260 |
|
3261 |
|
3262 | Document.prototype.execPopulate = function(callback) {
|
3263 | return utils.promiseOrCallback(callback, cb => {
|
3264 | this.populate(cb);
|
3265 | }, this.constructor.events);
|
3266 | };
|
3267 |
|
3268 |
|
3269 |
|
3270 |
|
3271 |
|
3272 |
|
3273 |
|
3274 |
|
3275 |
|
3276 |
|
3277 |
|
3278 |
|
3279 |
|
3280 |
|
3281 |
|
3282 |
|
3283 |
|
3284 |
|
3285 |
|
3286 |
|
3287 | Document.prototype.populated = function(path, val, options) {
|
3288 |
|
3289 | if (val === null || val === void 0) {
|
3290 | if (!this.$__.populated) {
|
3291 | return undefined;
|
3292 | }
|
3293 | const v = this.$__.populated[path];
|
3294 | if (v) {
|
3295 | return v.value;
|
3296 | }
|
3297 | return undefined;
|
3298 | }
|
3299 |
|
3300 |
|
3301 | if (val === true) {
|
3302 | if (!this.$__.populated) {
|
3303 | return undefined;
|
3304 | }
|
3305 | return this.$__.populated[path];
|
3306 | }
|
3307 |
|
3308 | this.$__.populated || (this.$__.populated = {});
|
3309 | this.$__.populated[path] = {value: val, options: options};
|
3310 |
|
3311 |
|
3312 |
|
3313 | const pieces = path.split('.');
|
3314 | for (let i = 0; i < pieces.length - 1; ++i) {
|
3315 | const subpath = pieces.slice(0, i + 1).join('.');
|
3316 | const subdoc = this.get(subpath);
|
3317 | if (subdoc != null && subdoc.$__ != null && this.populated(subpath)) {
|
3318 | const rest = pieces.slice(i + 1).join('.');
|
3319 | subdoc.populated(rest, val, options);
|
3320 |
|
3321 |
|
3322 | break;
|
3323 | }
|
3324 | }
|
3325 |
|
3326 | return val;
|
3327 | };
|
3328 |
|
3329 |
|
3330 |
|
3331 |
|
3332 |
|
3333 |
|
3334 |
|
3335 |
|
3336 |
|
3337 |
|
3338 |
|
3339 |
|
3340 |
|
3341 |
|
3342 |
|
3343 |
|
3344 |
|
3345 |
|
3346 |
|
3347 |
|
3348 |
|
3349 |
|
3350 | Document.prototype.depopulate = function(path) {
|
3351 | if (typeof path === 'string') {
|
3352 | path = path.split(' ');
|
3353 | }
|
3354 | let populatedIds;
|
3355 | const virtualKeys = this.$$populatedVirtuals ? Object.keys(this.$$populatedVirtuals) : [];
|
3356 | const populated = get(this, '$__.populated', {});
|
3357 |
|
3358 | if (arguments.length === 0) {
|
3359 |
|
3360 | for (let i = 0; i < virtualKeys.length; i++) {
|
3361 | delete this.$$populatedVirtuals[virtualKeys[i]];
|
3362 | delete this._doc[virtualKeys[i]];
|
3363 | delete populated[virtualKeys[i]];
|
3364 | }
|
3365 |
|
3366 | const keys = Object.keys(populated);
|
3367 |
|
3368 | for (let i = 0; i < keys.length; i++) {
|
3369 | populatedIds = this.populated(keys[i]);
|
3370 | if (!populatedIds) {
|
3371 | continue;
|
3372 | }
|
3373 | delete populated[keys[i]];
|
3374 | this.$set(keys[i], populatedIds);
|
3375 | }
|
3376 | return this;
|
3377 | }
|
3378 |
|
3379 | for (let i = 0; i < path.length; i++) {
|
3380 | populatedIds = this.populated(path[i]);
|
3381 | delete populated[path[i]];
|
3382 |
|
3383 | if (virtualKeys.indexOf(path[i]) !== -1) {
|
3384 | delete this.$$populatedVirtuals[path[i]];
|
3385 | delete this._doc[path[i]];
|
3386 | } else if (populatedIds) {
|
3387 | this.$set(path[i], populatedIds);
|
3388 | }
|
3389 | }
|
3390 | return this;
|
3391 | };
|
3392 |
|
3393 |
|
3394 | /**
|
3395 | * Returns the full path to this document.
|
3396 | *
|
3397 | * @param {String} [path]
|
3398 | * @return {String}
|
3399 | * @api private
|
3400 | * @method $__fullPath
|
3401 | * @memberOf Document
|
3402 | * @instance
|
3403 | */
|
3404 |
|
3405 | Document.prototype.$__fullPath = function(path) {
|
3406 |
|
3407 | return path || '';
|
3408 | };
|
3409 |
|
3410 |
|
3411 |
|
3412 |
|
3413 |
|
3414 | Document.ValidationError = ValidationError;
|
3415 | module.exports = exports = Document;
|