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