-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
document.js
3188 lines (2790 loc) · 83.8 KB
/
document.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
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
693
694
695
696
697
698
699
700
701
702
703
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
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
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
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
/*!
* Module dependencies.
*/
const EventEmitter = require('events').EventEmitter;
const InternalCache = require('./internal');
const MongooseError = require('./error');
const MixedSchema = require('./schema/mixed');
const ObjectExpectedError = require('./error/objectExpected');
const ObjectParameterError = require('./error/objectParameter');
const StrictModeError = require('./error/strict');
const ValidatorError = require('./schematype').ValidatorError;
const VirtualType = require('./virtualtype');
const cleanModifiedSubpaths = require('./helpers/document/cleanModifiedSubpaths');
const compile = require('./helpers/document/compile').compile;
const defineKey = require('./helpers/document/compile').defineKey;
const flatten = require('./helpers/common').flatten;
const get = require('./helpers/get');
const getEmbeddedDiscriminatorPath = require('./helpers/document/getEmbeddedDiscriminatorPath');
const idGetter = require('./plugins/idGetter');
const isDefiningProjection = require('./helpers/projection/isDefiningProjection');
const isExclusive = require('./helpers/projection/isExclusive');
const inspect = require('util').inspect;
const internalToObjectOptions = require('./options').internalToObjectOptions;
const mpath = require('mpath');
const utils = require('./utils');
const ValidationError = MongooseError.ValidationError;
const clone = utils.clone;
const deepEqual = utils.deepEqual;
const isMongooseObject = utils.isMongooseObject;
const documentArrayParent = require('./helpers/symbols').documentArrayParent;
const getSymbol = require('./helpers/symbols').getSymbol;
let DocumentArray;
let MongooseArray;
let Embedded;
const specialProperties = utils.specialProperties;
/**
* The core Mongoose document constructor. You should not call this directly,
* the Mongoose [Model constructor](./api.html#Model) calls this for you.
*
* @param {Object} obj the values to set
* @param {Object} [fields] optional object containing the fields which were selected in the query returning this document and any populated paths data
* @param {Boolean} [skipId] bool, should we auto create an ObjectId _id
* @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter
* @event `init`: Emitted on a document after it has was retreived from the db and fully hydrated by Mongoose.
* @event `save`: Emitted when the document is successfully saved
* @api private
*/
function Document(obj, fields, skipId, options) {
if (typeof skipId === 'object' && skipId != null) {
options = skipId;
skipId = options.skipId;
}
options = options || {};
this.$__ = new InternalCache;
this.$__.emitter = new EventEmitter();
this.isNew = 'isNew' in options ? options.isNew : true;
this.errors = undefined;
this.$__.$options = options || {};
if (obj != null && typeof obj !== 'object') {
throw new ObjectParameterError(obj, 'obj', 'Document');
}
const schema = this.schema;
if (typeof fields === 'boolean') {
this.$__.strictMode = fields;
fields = undefined;
} else {
this.$__.strictMode = schema.options.strict;
this.$__.selected = fields;
}
const required = schema.requiredPaths(true);
for (let i = 0; i < required.length; ++i) {
this.$__.activePaths.require(required[i]);
}
this.$__.emitter.setMaxListeners(0);
let exclude = null;
// determine if this doc is a result of a query with
// excluded fields
if (fields && utils.getFunctionName(fields.constructor) === 'Object') {
exclude = isExclusive(fields);
}
const hasIncludedChildren = exclude === false && fields ?
$__hasIncludedChildren(fields) :
{};
this.$__buildDoc(obj, fields, skipId, exclude, hasIncludedChildren, false);
// By default, defaults get applied **before** setting initial values
// Re: gh-6155
$__applyDefaults(this, fields, skipId, exclude, hasIncludedChildren, true, {
isNew: this.isNew
});
if (obj) {
if (obj instanceof Document) {
this.isNew = obj.isNew;
}
// Skip set hooks
if (this.$__original_set) {
this.$__original_set(obj, undefined, true);
} else {
this.$set(obj, undefined, true);
}
}
// Function defaults get applied **after** setting initial values so they
// see the full doc rather than an empty one, unless they opt out.
// Re: gh-3781, gh-6155
if (options.willInit) {
this.once('init', () => {
$__applyDefaults(this, fields, skipId, exclude, hasIncludedChildren, false, options.skipDefaults, {
isNew: this.isNew
});
});
} else {
$__applyDefaults(this, fields, skipId, exclude, hasIncludedChildren, false, options.skipDefaults, {
isNew: this.isNew
});
}
this.$__._id = this._id;
if (!schema.options.strict && obj) {
const _this = this;
const keys = Object.keys(this._doc);
keys.forEach(function(key) {
if (!(key in schema.tree)) {
defineKey(key, null, _this);
}
});
}
applyQueue(this);
}
/*!
* Document exposes the NodeJS event emitter API, so you can use
* `on`, `once`, etc.
*/
utils.each(
['on', 'once', 'emit', 'listeners', 'removeListener', 'setMaxListeners',
'removeAllListeners', 'addListener'],
function(emitterFn) {
Document.prototype[emitterFn] = function() {
return this.$__.emitter[emitterFn].apply(this.$__.emitter, arguments);
};
});
Document.prototype.constructor = Document;
/**
* The documents schema.
*
* @api public
* @property schema
* @memberOf Document
* @instance
*/
Document.prototype.schema;
/**
* Boolean flag specifying if the document is new.
*
* @api public
* @property isNew
* @memberOf Document
* @instance
*/
Document.prototype.isNew;
/**
* The string version of this documents _id.
*
* ####Note:
*
* This getter exists on all documents by default. The getter can be disabled by setting the `id` [option](/docs/guide.html#id) of its `Schema` to false at construction time.
*
* new Schema({ name: String }, { id: false });
*
* @api public
* @see Schema options /docs/guide.html#options
* @property id
* @memberOf Document
* @instance
*/
Document.prototype.id;
/**
* Hash containing current validation errors.
*
* @api public
* @property errors
* @memberOf Document
* @instance
*/
Document.prototype.errors;
/*!
* ignore
*/
function $__hasIncludedChildren(fields) {
const hasIncludedChildren = {};
const keys = Object.keys(fields);
for (let j = 0; j < keys.length; ++j) {
const parts = keys[j].split('.');
const c = [];
for (let k = 0; k < parts.length; ++k) {
c.push(parts[k]);
hasIncludedChildren[c.join('.')] = 1;
}
}
return hasIncludedChildren;
}
/*!
* ignore
*/
function $__applyDefaults(doc, fields, skipId, exclude, hasIncludedChildren, isBeforeSetters, pathsToSkip) {
const paths = Object.keys(doc.schema.paths);
const plen = paths.length;
for (let i = 0; i < plen; ++i) {
let def;
let curPath = '';
const p = paths[i];
if (p === '_id' && skipId) {
continue;
}
const type = doc.schema.paths[p];
const path = p.split('.');
const len = path.length;
let included = false;
let doc_ = doc._doc;
for (let j = 0; j < len; ++j) {
if (doc_ == null) {
break;
}
const piece = path[j];
curPath += (!curPath.length ? '' : '.') + piece;
if (exclude === true) {
if (curPath in fields) {
break;
}
} else if (exclude === false && fields && !included) {
if (curPath in fields) {
included = true;
} else if (!hasIncludedChildren[curPath]) {
break;
}
}
if (j === len - 1) {
if (doc_[piece] !== void 0) {
break;
}
if (typeof type.defaultValue === 'function') {
if (!type.defaultValue.$runBeforeSetters && isBeforeSetters) {
break;
}
if (type.defaultValue.$runBeforeSetters && !isBeforeSetters) {
break;
}
} else if (!isBeforeSetters) {
// Non-function defaults should always run **before** setters
continue;
}
if (pathsToSkip && pathsToSkip[curPath]) {
break;
}
if (fields && exclude !== null) {
if (exclude === true) {
// apply defaults to all non-excluded fields
if (p in fields) {
continue;
}
def = type.getDefault(doc, false);
if (typeof def !== 'undefined') {
doc_[piece] = def;
doc.$__.activePaths.default(p);
}
} else if (included) {
// selected field
def = type.getDefault(doc, false);
if (typeof def !== 'undefined') {
doc_[piece] = def;
doc.$__.activePaths.default(p);
}
}
} else {
def = type.getDefault(doc, false);
if (typeof def !== 'undefined') {
doc_[piece] = def;
doc.$__.activePaths.default(p);
}
}
} else {
doc_ = doc_[piece];
}
}
}
}
/**
* Builds the default doc structure
*
* @param {Object} obj
* @param {Object} [fields]
* @param {Boolean} [skipId]
* @api private
* @method $__buildDoc
* @memberOf Document
* @instance
*/
Document.prototype.$__buildDoc = function(obj, fields, skipId, exclude, hasIncludedChildren) {
const doc = {};
const paths = Object.keys(this.schema.paths).
// Don't build up any paths that are underneath a map, we don't know
// what the keys will be
filter(p => !p.includes('$*'));
const plen = paths.length;
let ii = 0;
for (; ii < plen; ++ii) {
const p = paths[ii];
if (p === '_id') {
if (skipId) {
continue;
}
if (obj && '_id' in obj) {
continue;
}
}
const path = p.split('.');
const len = path.length;
const last = len - 1;
let curPath = '';
let doc_ = doc;
let included = false;
for (let i = 0; i < len; ++i) {
const piece = path[i];
curPath += (!curPath.length ? '' : '.') + piece;
// support excluding intermediary levels
if (exclude === true) {
if (curPath in fields) {
break;
}
} else if (exclude === false && fields && !included) {
if (curPath in fields) {
included = true;
} else if (!hasIncludedChildren[curPath]) {
break;
}
}
if (i < last) {
doc_ = doc_[piece] || (doc_[piece] = {});
}
}
}
this._doc = doc;
};
/*!
* Converts to POJO when you use the document for querying
*/
Document.prototype.toBSON = function() {
return this.toObject(internalToObjectOptions);
};
/**
* Initializes the document without setters or marking anything modified.
*
* Called internally after a document is returned from mongodb. Normally,
* you do **not** need to call this function on your own.
*
* This function triggers `init` [middleware](/docs/middleware.html).
* Note that `init` hooks are [synchronous](/docs/middleware.html#synchronous).
*
* @param {Object} doc document returned by mongo
* @api public
* @memberOf Document
* @instance
*/
Document.prototype.init = function(doc, opts, fn) {
if (typeof opts === 'function') {
fn = opts;
opts = null;
}
this.$__init(doc, opts);
if (fn) {
fn(null, this);
}
return this;
};
/*!
* ignore
*/
Document.prototype.$__init = function(doc, opts) {
this.isNew = false;
this.$init = true;
// handle docs with populated paths
// If doc._id is not null or undefined
if (doc._id !== null && doc._id !== undefined &&
opts && opts.populated && opts.populated.length) {
const id = String(doc._id);
for (let i = 0; i < opts.populated.length; ++i) {
const item = opts.populated[i];
if (item.isVirtual) {
this.populated(item.path, utils.getValue(item.path, doc), item);
} else {
this.populated(item.path, item._docs[id], item);
}
}
}
init(this, doc, this._doc);
this.emit('init', this);
this.constructor.emit('init', this);
this.$__._id = this._id;
return this;
};
/*!
* Init helper.
*
* @param {Object} self document instance
* @param {Object} obj raw mongodb doc
* @param {Object} doc object we are initializing
* @api private
*/
function init(self, obj, doc, prefix) {
prefix = prefix || '';
const keys = Object.keys(obj);
const len = keys.length;
let schema;
let path;
let i;
let index = 0;
while (index < len) {
_init(index++);
}
function _init(index) {
i = keys[index];
path = prefix + i;
schema = self.schema.path(path);
// Should still work if not a model-level discriminator, but should not be
// necessary. This is *only* to catch the case where we queried using the
// base model and the discriminated model has a projection
if (self.schema.$isRootDiscriminator && !self.isSelected(path)) {
return;
}
if (!schema && utils.isObject(obj[i]) &&
(!obj[i].constructor || utils.getFunctionName(obj[i].constructor) === 'Object')) {
// assume nested object
if (!doc[i]) {
doc[i] = {};
}
init(self, obj[i], doc[i], path + '.');
} else if (!schema) {
doc[i] = obj[i];
} else {
if (obj[i] === null) {
doc[i] = null;
} else if (obj[i] !== undefined) {
const intCache = obj[i].$__ || {};
const wasPopulated = intCache.wasPopulated || null;
if (schema && !wasPopulated) {
try {
doc[i] = schema.cast(obj[i], self, true);
} catch (e) {
self.invalidate(e.path, new ValidatorError({
path: e.path,
message: e.message,
type: 'cast',
value: e.value
}));
}
} else {
doc[i] = obj[i];
}
}
// mark as hydrated
if (!self.isModified(path)) {
self.$__.activePaths.init(path);
}
}
}
}
/**
* Sends an update command with this document `_id` as the query selector.
*
* ####Example:
*
* weirdCar.update({$inc: {wheels:1}}, { w: 1 }, callback);
*
* ####Valid options:
*
* - same as in [Model.update](#model_Model.update)
*
* @see Model.update #model_Model.update
* @param {Object} doc
* @param {Object} options
* @param {Function} callback
* @return {Query}
* @api public
* @memberOf Document
* @instance
*/
Document.prototype.update = function update() {
const args = utils.args(arguments);
args.unshift({_id: this._id});
const query = this.constructor.update.apply(this.constructor, args);
if (this.$session() != null) {
if (!('session' in query.options)) {
query.options.session = this.$session();
}
}
return query;
};
/**
* Sends an updateOne command with this document `_id` as the query selector.
*
* ####Example:
*
* weirdCar.updateOne({$inc: {wheels:1}}, { w: 1 }, callback);
*
* ####Valid options:
*
* - same as in [Model.updateOne](#model_Model.updateOne)
*
* @see Model.updateOne #model_Model.updateOne
* @param {Object} doc
* @param {Object} options
* @param {Function} callback
* @return {Query}
* @api public
* @memberOf Document
* @instance
*/
Document.prototype.updateOne = function updateOne(doc, options, callback) {
const query = this.constructor.updateOne({_id: this._id}, doc, options);
query._pre(cb => {
this.constructor._middleware.execPre('updateOne', this, [], cb);
});
query._post(cb => {
this.constructor._middleware.execPost('updateOne', this, [], {}, cb);
});
if (this.$session() != null) {
if (!('session' in query.options)) {
query.options.session = this.$session();
}
}
if (callback != null) {
return query.exec(callback);
}
return query;
};
/**
* Sends a replaceOne command with this document `_id` as the query selector.
*
* ####Valid options:
*
* - same as in [Model.replaceOne](#model_Model.replaceOne)
*
* @see Model.replaceOne #model_Model.replaceOne
* @param {Object} doc
* @param {Object} options
* @param {Function} callback
* @return {Query}
* @api public
* @memberOf Document
* @instance
*/
Document.prototype.replaceOne = function replaceOne() {
const args = utils.args(arguments);
args.unshift({ _id: this._id });
return this.constructor.replaceOne.apply(this.constructor, args);
};
/**
* Getter/setter around the session associated with this document. Used to
* automatically set `session` if you `save()` a doc that you got from a
* query with an associated session.
*
* ####Example:
*
* const session = MyModel.startSession();
* const doc = await MyModel.findOne().session(session);
* doc.$session() === session; // true
* doc.$session(null);
* doc.$session() === null; // true
*
* If this is a top-level document, setting the session propagates to all child
* docs.
*
* @param {ClientSession} [session] overwrite the current session
* @return {ClientSession}
* @method $session
* @api public
* @memberOf Document
*/
Document.prototype.$session = function $session(session) {
if (arguments.length === 0) {
return this.$__.session;
}
this.$__.session = session;
if (!this.ownerDocument) {
const subdocs = this.$__getAllSubdocs();
for (const child of subdocs) {
child.$session(session);
}
}
return session;
};
/**
* Alias for `set()`, used internally to avoid conflicts
*
* @param {String|Object} path path or object of key/vals to set
* @param {Any} val the value to set
* @param {Schema|String|Number|Buffer|*} [type] optionally specify a type for "on-the-fly" attributes
* @param {Object} [options] optionally specify options that modify the behavior of the set
* @method $set
* @name $set
* @memberOf Document
* @instance
* @api public
*/
Document.prototype.$set = function $set(path, val, type, options) {
if (type && utils.getFunctionName(type.constructor) === 'Object') {
options = type;
type = undefined;
}
options = options || {};
const merge = options.merge;
const adhoc = type && type !== true;
const constructing = type === true;
let adhocs;
let keys;
let i = 0;
let pathtype;
let key;
let prefix;
const strict = 'strict' in options
? options.strict
: this.$__.strictMode;
if (adhoc) {
adhocs = this.$__.adhocPaths || (this.$__.adhocPaths = {});
adhocs[path] = this.schema.interpretAsType(path, type, this.schema.options);
}
if (typeof path !== 'string') {
// new Document({ key: val })
if (path === null || path === void 0) {
const _ = path;
path = val;
val = _;
} else {
prefix = val ? val + '.' : '';
if (path instanceof Document) {
if (path.$__isNested) {
path = path.toObject();
} else {
path = path._doc;
}
}
keys = Object.keys(path);
const len = keys.length;
if (len === 0 && !this.schema.options.minimize) {
if (val) {
this.$set(val, {});
}
return this;
}
while (i < len) {
_handleIndex.call(this, i++);
}
return this;
}
}
function _handleIndex(i) {
key = keys[i];
const pathName = prefix + key;
pathtype = this.schema.pathType(pathName);
// On initial set, delete any nested keys if we're going to overwrite
// them to ensure we keep the user's key order.
if (type === true &&
!prefix &&
path[key] != null &&
pathtype === 'nested' &&
this._doc[key] != null &&
Object.keys(this._doc[key]).length === 0) {
delete this._doc[key];
}
if (path[key] !== null &&
path[key] !== void 0 &&
// need to know if plain object - no Buffer, ObjectId, ref, etc
utils.isObject(path[key]) &&
(!path[key].constructor || utils.getFunctionName(path[key].constructor) === 'Object') &&
pathtype !== 'virtual' &&
pathtype !== 'real' &&
!(this.$__path(pathName) instanceof MixedSchema) &&
!(this.schema.paths[pathName] &&
this.schema.paths[pathName].options &&
this.schema.paths[pathName].options.ref)) {
this.$set(path[key], prefix + key, constructing);
} else if (strict) {
// Don't overwrite defaults with undefined keys (gh-3981)
if (constructing && path[key] === void 0 &&
this.get(key) !== void 0) {
return;
}
if (pathtype === 'adhocOrUndefined') {
pathtype = getEmbeddedDiscriminatorPath(this, pathName, { typeOnly: true });
}
if (pathtype === 'real' || pathtype === 'virtual') {
// Check for setting single embedded schema to document (gh-3535)
let p = path[key];
if (this.schema.paths[pathName] &&
this.schema.paths[pathName].$isSingleNested &&
path[key] instanceof Document) {
p = p.toObject({ virtuals: false, transform: false });
}
this.$set(prefix + key, p, constructing);
} else if (pathtype === 'nested' && path[key] instanceof Document) {
this.$set(prefix + key,
path[key].toObject({transform: false}), constructing);
} else if (strict === 'throw') {
if (pathtype === 'nested') {
throw new ObjectExpectedError(key, path[key]);
} else {
throw new StrictModeError(key);
}
}
} else if (path[key] !== void 0) {
this.$set(prefix + key, path[key], constructing);
}
}
const pathType = this.schema.pathType(path);
if (pathType === 'nested' && val) {
if (utils.isObject(val) &&
(!val.constructor || utils.getFunctionName(val.constructor) === 'Object')) {
if (!merge) {
this.setValue(path, null);
cleanModifiedSubpaths(this, path);
} else {
return this.$set(val, path, constructing);
}
const keys = Object.keys(val);
this.setValue(path, {});
for (const key of keys) {
this.$set(path + '.' + key, val[key], constructing);
}
this.markModified(path);
cleanModifiedSubpaths(this, path, { skipDocArrays: true });
return this;
}
this.invalidate(path, new MongooseError.CastError('Object', val, path));
return this;
}
let schema;
const parts = path.split('.');
if (pathType === 'adhocOrUndefined' && strict) {
// check for roots that are Mixed types
let mixed;
for (i = 0; i < parts.length; ++i) {
const subpath = parts.slice(0, i + 1).join('.');
// If path is underneath a virtual, bypass everything and just set it.
if (i + 1 < parts.length && this.schema.pathType(subpath) === 'virtual') {
mpath.set(path, val, this);
return this;
}
schema = this.schema.path(subpath);
if (schema == null) {
continue;
}
if (schema instanceof MixedSchema) {
// allow changes to sub paths of mixed types
mixed = true;
break;
}
}
if (schema == null) {
// Check for embedded discriminators
schema = getEmbeddedDiscriminatorPath(this, path);
}
if (!mixed && !schema) {
if (strict === 'throw') {
throw new StrictModeError(path);
}
return this;
}
} else if (pathType === 'virtual') {
schema = this.schema.virtualpath(path);
schema.applySetters(val, this);
return this;
} else {
schema = this.$__path(path);
}
// gh-4578, if setting a deeply nested path that doesn't exist yet, create it
let cur = this._doc;
let curPath = '';
for (i = 0; i < parts.length - 1; ++i) {
cur = cur[parts[i]];
curPath += (curPath.length > 0 ? '.' : '') + parts[i];
if (!cur) {
this.$set(curPath, {});
// Hack re: gh-5800. If nested field is not selected, it probably exists
// so `MongoError: cannot use the part (nested of nested.num) to
// traverse the element ({nested: null})` is not likely. If user gets
// that error, its their fault for now. We should reconsider disallowing
// modifying not selected paths for 6.x
if (!this.isSelected(curPath)) {
this.unmarkModified(curPath);
}
cur = this.getValue(curPath);
}
}
let pathToMark;
// When using the $set operator the path to the field must already exist.
// Else mongodb throws: "LEFT_SUBFIELD only supports Object"
if (parts.length <= 1) {
pathToMark = path;
} else {
for (i = 0; i < parts.length; ++i) {
const subpath = parts.slice(0, i + 1).join('.');
if (this.get(subpath) === null) {
pathToMark = subpath;
break;
}
}
if (!pathToMark) {
pathToMark = path;
}
}
// if this doc is being constructed we should not trigger getters
const priorVal = (() => {
if (this.$__.$options.priorDoc != null) {
return this.$__.$options.priorDoc.getValue(path);
}
if (constructing) {
return void 0;
}
return this.getValue(path);
})();
if (!schema) {
this.$__set(pathToMark, path, constructing, parts, schema, val, priorVal);
return this;
}
let shouldSet = true;
try {
// If the user is trying to set a ref path to a document with
// the correct model name, treat it as populated
const refMatches = (() => {
if (schema.options == null) {
return false;
}
if (!(val instanceof Document)) {
return false;
}
const model = val.constructor;
// Check ref
const ref = schema.options.ref;
if (ref != null && (ref === model.modelName || ref === model.baseModelName)) {
return true;
}
// Check refPath
const refPath = schema.options.refPath;
if (refPath == null) {
return false;
}
const modelName = val.get(refPath);
if (modelName === model.modelName || modelName === model.baseModelName) {
return true;
}
return false;
})();
let didPopulate = false;
if (refMatches && val instanceof Document) {
if (this.ownerDocument) {
this.ownerDocument().populated(this.$__fullPath(path),
val._id, {model: val.constructor});
} else {
this.populated(path, val._id, {model: val.constructor});
}
didPopulate = true;
}
let popOpts;
if (schema.options &&
Array.isArray(schema.options[this.schema.options.typeKey]) &&
schema.options[this.schema.options.typeKey].length &&