forked from Automattic/mongoose
-
Notifications
You must be signed in to change notification settings - Fork 0
/
document.js
4674 lines (4084 loc) · 134 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/index');
const MixedSchema = require('./schema/mixed');
const ObjectExpectedError = require('./error/objectExpected');
const ObjectParameterError = require('./error/objectParameter');
const ParallelValidateError = require('./error/parallelValidate');
const Schema = require('./schema');
const StrictModeError = require('./error/strict');
const ValidationError = require('./error/validation');
const ValidatorError = require('./error/validator');
const $__hasIncludedChildren = require('./helpers/projection/hasIncludedChildren');
const applyDefaults = require('./helpers/document/applyDefaults');
const cleanModifiedSubpaths = require('./helpers/document/cleanModifiedSubpaths');
const clone = require('./helpers/clone');
const compile = require('./helpers/document/compile').compile;
const defineKey = require('./helpers/document/compile').defineKey;
const flatten = require('./helpers/common').flatten;
const flattenObjectWithDottedPaths = require('./helpers/path/flattenObjectWithDottedPaths');
const get = require('./helpers/get');
const getEmbeddedDiscriminatorPath = require('./helpers/document/getEmbeddedDiscriminatorPath');
const getKeysInSchemaOrder = require('./helpers/schema/getKeysInSchemaOrder');
const handleSpreadDoc = require('./helpers/document/handleSpreadDoc');
const immediate = require('./helpers/immediate');
const isDefiningProjection = require('./helpers/projection/isDefiningProjection');
const isExclusive = require('./helpers/projection/isExclusive');
const inspect = require('util').inspect;
const internalToObjectOptions = require('./options').internalToObjectOptions;
const markArraySubdocsPopulated = require('./helpers/populate/markArraySubdocsPopulated');
const mpath = require('mpath');
const queryhelpers = require('./queryhelpers');
const utils = require('./utils');
const isPromise = require('./helpers/isPromise');
const deepEqual = utils.deepEqual;
const isMongooseObject = utils.isMongooseObject;
const arrayAtomicsBackupSymbol = require('./helpers/symbols').arrayAtomicsBackupSymbol;
const arrayAtomicsSymbol = require('./helpers/symbols').arrayAtomicsSymbol;
const documentArrayParent = require('./helpers/symbols').documentArrayParent;
const documentIsModified = require('./helpers/symbols').documentIsModified;
const documentModifiedPaths = require('./helpers/symbols').documentModifiedPaths;
const documentSchemaSymbol = require('./helpers/symbols').documentSchemaSymbol;
const getSymbol = require('./helpers/symbols').getSymbol;
const populateModelSymbol = require('./helpers/symbols').populateModelSymbol;
const scopeSymbol = require('./helpers/symbols').scopeSymbol;
const schemaMixedSymbol = require('./schema/symbols').schemaMixedSymbol;
const parentPaths = require('./helpers/path/parentPaths');
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/model.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 {Object} [options] various configuration options for the document
* @param {Boolean} [options.defaults=true] if `false`, skip applying default values to this document.
* @inherits NodeJS EventEmitter https://nodejs.org/api/events.html#class-eventemitter
* @event `init`: Emitted on a document after it has been retrieved 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 = Object.assign({}, options);
// Support `browserDocument.js` syntax
if (this.$__schema == null) {
const _schema = utils.isObject(fields) && !fields.instanceOfSchema ?
new Schema(fields) :
fields;
this.$__setSchema(_schema);
fields = skipId;
skipId = options;
options = arguments[4] || {};
}
this.$__ = new InternalCache();
// Avoid setting `isNew` to `true`, because it is `true` by default
if (options.isNew != null && options.isNew !== true) {
this.$isNew = options.isNew;
}
if (options.priorDoc != null) {
this.$__.priorDoc = options.priorDoc;
}
if (skipId) {
this.$__.skipId = skipId;
}
if (obj != null && typeof obj !== 'object') {
throw new ObjectParameterError(obj, 'obj', 'Document');
}
let defaults = true;
if (options.defaults !== undefined) {
this.$__.defaults = options.defaults;
defaults = options.defaults;
}
const schema = this.$__schema;
if (typeof fields === 'boolean' || fields === 'throw') {
if (fields !== true) {
this.$__.strictMode = fields;
}
fields = undefined;
} else if (schema.options.strict !== true) {
this.$__.strictMode = schema.options.strict;
}
const requiredPaths = schema.requiredPaths(true);
for (const path of requiredPaths) {
this.$__.activePaths.require(path);
}
let exclude = null;
// determine if this doc is a result of a query with
// excluded fields
if (utils.isPOJO(fields) && Object.keys(fields).length > 0) {
exclude = isExclusive(fields);
this.$__.selected = fields;
this.$__.exclude = exclude;
}
const hasIncludedChildren = exclude === false && fields ?
$__hasIncludedChildren(fields) :
null;
if (this._doc == null) {
this.$__buildDoc(obj, fields, skipId, exclude, hasIncludedChildren, false);
// By default, defaults get applied **before** setting initial values
// Re: gh-6155
if (defaults) {
applyDefaults(this, fields, exclude, hasIncludedChildren, true, null);
}
}
if (obj) {
// Skip set hooks
if (this.$__original_set) {
this.$__original_set(obj, undefined, true, options);
} else {
this.$set(obj, undefined, true, options);
}
if (obj instanceof Document) {
this.$isNew = obj.$isNew;
}
}
// 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 && defaults) {
if (options.skipDefaults) {
this.$__.skipDefaults = options.skipDefaults;
}
} else if (defaults) {
applyDefaults(this, fields, exclude, hasIncludedChildren, false, options.skipDefaults);
}
if (!this.$__.strictMode && obj) {
const _this = this;
const keys = Object.keys(this._doc);
keys.forEach(function(key) {
// Avoid methods, virtuals, existing fields, and `$` keys. The latter is to avoid overwriting
// Mongoose internals.
if (!(key in schema.tree) && !(key in schema.methods) && !(key in schema.virtuals) && !key.startsWith('$')) {
defineKey({ prop: key, subprops: null, prototype: _this });
}
});
}
applyQueue(this);
}
Document.prototype.$isMongooseDocumentPrototype = true;
/**
* Boolean flag specifying if the document is new. If you create a document
* using `new`, this document will be considered "new". `$isNew` is how
* Mongoose determines whether `save()` should use `insertOne()` to create
* a new document or `updateOne()` to update an existing document.
*
* #### Example:
*
* const user = new User({ name: 'John Smith' });
* user.$isNew; // true
*
* await user.save(); // Sends an `insertOne` to MongoDB
*
* On the other hand, if you load an existing document from the database
* using `findOne()` or another [query operation](/docs/queries.html),
* `$isNew` will be false.
*
* #### Example:
*
* const user = await User.findOne({ name: 'John Smith' });
* user.$isNew; // false
*
* Mongoose sets `$isNew` to `false` immediately after `save()` succeeds.
* That means Mongoose sets `$isNew` to false **before** `post('save')` hooks run.
* In `post('save')` hooks, `$isNew` will be `false` if `save()` succeeded.
*
* #### Example:
*
* userSchema.post('save', function() {
* this.$isNew; // false
* });
* await User.create({ name: 'John Smith' });
*
* For subdocuments, `$isNew` is true if either the parent has `$isNew` set,
* or if you create a new subdocument.
*
* #### Example:
*
* // Assume `Group` has a document array `users`
* const group = await Group.findOne();
* group.users[0].$isNew; // false
*
* group.users.push({ name: 'John Smith' });
* group.users[1].$isNew; // true
*
* @api public
* @property $isNew
* @memberOf Document
* @instance
*/
Object.defineProperty(Document.prototype, 'isNew', {
get: function() {
return this.$isNew;
},
set: function(value) {
this.$isNew = value;
}
});
/**
* Hash containing current validation errors.
*
* @api public
* @property errors
* @memberOf Document
* @instance
*/
Object.defineProperty(Document.prototype, 'errors', {
get: function() {
return this.$errors;
},
set: function(value) {
this.$errors = value;
}
});
/*!
* ignore
*/
Document.prototype.$isNew = true;
/*!
* 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() {
// Delay creating emitter until necessary because emitters take up a lot of memory,
// especially for subdocuments.
if (!this.$__.emitter) {
if (emitterFn === 'emit') {
return;
}
this.$__.emitter = new EventEmitter();
this.$__.emitter.setMaxListeners(0);
}
return this.$__.emitter[emitterFn].apply(this.$__.emitter, arguments);
};
Document.prototype[`$${emitterFn}`] = Document.prototype[emitterFn];
});
Document.prototype.constructor = Document;
for (const i in EventEmitter.prototype) {
Document[i] = EventEmitter.prototype[i];
}
/**
* The document's internal schema.
*
* @api private
* @property schema
* @memberOf Document
* @instance
*/
Document.prototype.$__schema;
/**
* The document's schema.
*
* @api public
* @property schema
* @memberOf Document
* @instance
*/
Document.prototype.schema;
/**
* Empty object that you can use for storing properties on the document. This
* is handy for passing data to middleware without conflicting with Mongoose
* internals.
*
* #### Example:
*
* schema.pre('save', function() {
* // Mongoose will set `isNew` to `false` if `save()` succeeds
* this.$locals.wasNew = this.isNew;
* });
*
* schema.post('save', function() {
* // Prints true if `isNew` was set before `save()`
* console.log(this.$locals.wasNew);
* });
*
* @api public
* @property $locals
* @memberOf Document
* @instance
*/
Object.defineProperty(Document.prototype, '$locals', {
configurable: false,
enumerable: false,
get: function() {
if (this.$__.locals == null) {
this.$__.locals = {};
}
return this.$__.locals;
},
set: function(v) {
this.$__.locals = v;
}
});
/**
* Legacy alias for `$isNew`.
*
* @api public
* @property isNew
* @memberOf Document
* @see $isNew #document_Document-$isNew
* @instance
*/
Document.prototype.isNew;
/**
* Set this property to add additional query filters when Mongoose saves this document and `isNew` is false.
*
* #### Example:
*
* // Make sure `save()` never updates a soft deleted document.
* schema.pre('save', function() {
* this.$where = { isDeleted: false };
* });
*
* @api public
* @property $where
* @memberOf Document
* @instance
*/
Object.defineProperty(Document.prototype, '$where', {
configurable: false,
enumerable: false,
writable: true
});
/**
* 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;
/**
* A string containing the current operation that Mongoose is executing
* on this document. May be `null`, `'save'`, `'validate'`, or `'remove'`.
*
* #### Example:
*
* const doc = new Model({ name: 'test' });
* doc.$op; // null
*
* const promise = doc.save();
* doc.$op; // 'save'
*
* await promise;
* doc.$op; // null
*
* @api public
* @property $op
* @memberOf Document
* @instance
*/
Object.defineProperty(Document.prototype, '$op', {
get: function() {
return this.$__.op || null;
},
set: function(value) {
this.$__.op = value;
}
});
/*!
* ignore
*/
function $applyDefaultsToNested(val, path, doc) {
if (val == null) {
return;
}
flattenObjectWithDottedPaths(val);
const paths = Object.keys(doc.$__schema.paths);
const plen = paths.length;
const pathPieces = path.indexOf('.') === -1 ? [path] : path.split('.');
for (let i = 0; i < plen; ++i) {
let curPath = '';
const p = paths[i];
if (!p.startsWith(path + '.')) {
continue;
}
const type = doc.$__schema.paths[p];
const pieces = type.splitPath().slice(pathPieces.length);
const len = pieces.length;
if (type.defaultValue === void 0) {
continue;
}
let cur = val;
for (let j = 0; j < len; ++j) {
if (cur == null) {
break;
}
const piece = pieces[j];
if (j === len - 1) {
if (cur[piece] !== void 0) {
break;
}
try {
const def = type.getDefault(doc, false);
if (def !== void 0) {
cur[piece] = def;
}
} catch (err) {
doc.invalidate(path + '.' + curPath, err);
break;
}
break;
}
curPath += (!curPath.length ? '' : '.') + piece;
cur[piece] = cur[piece] || {};
cur = cur[piece];
}
}
}
/**
* Builds the default doc structure
*
* @param {Object} obj
* @param {Object} [fields]
* @param {Boolean} [skipId]
* @param {Boolean} [exclude]
* @param {Object} [hasIncludedChildren]
* @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 = this.$__schema.paths[p].splitPath();
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];
if (!curPath.length) {
curPath = piece;
} else {
curPath += '.' + 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
* @param {Object} [opts]
* @param {Function} [fn]
* @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;
};
/**
* Alias for [`.init`](#document_Document-init)
*
* @api public
*/
Document.prototype.$init = function() {
return this.constructor.prototype.init.apply(this, arguments);
};
/**
* Internal "init" function
*
* @param {Document} doc
* @param {Object} [opts]
* @returns {Document} this
* @api private
*/
Document.prototype.$__init = function(doc, opts) {
this.$isNew = false;
opts = opts || {};
// handle docs with populated paths
// If doc._id is not null or undefined
if (doc._id != null && opts.populated && opts.populated.length) {
const id = String(doc._id);
for (const item of opts.populated) {
if (item.isVirtual) {
this.$populated(item.path, utils.getValue(item.path, doc), item);
} else {
this.$populated(item.path, item._docs[id], item);
}
if (item._childDocs == null) {
continue;
}
for (const child of item._childDocs) {
if (child == null || child.$__ == null) {
continue;
}
child.$__.parent = this;
}
item._childDocs = [];
}
}
init(this, doc, this._doc, opts);
markArraySubdocsPopulated(this, opts.populated);
this.$emit('init', this);
this.constructor.emit('init', this);
const hasIncludedChildren = this.$__.exclude === false && this.$__.selected ?
$__hasIncludedChildren(this.$__.selected) :
null;
applyDefaults(this, this.$__.selected, this.$__.exclude, hasIncludedChildren, false, this.$__.skipDefaults);
return this;
};
/**
* Init helper.
*
* @param {Object} self document instance
* @param {Object} obj raw mongodb doc
* @param {Object} doc object we are initializing
* @param {Object} [opts] Optional Options
* @param {Boolean} [opts.setters] Call `applySetters` instead of `cast`
* @param {String} [prefix] Prefix to add to each path
* @api private
*/
function init(self, obj, doc, opts, prefix) {
prefix = prefix || '';
if (obj.$__ != null) {
obj = obj._doc;
}
const keys = Object.keys(obj);
const len = keys.length;
let schemaType;
let path;
let i;
let index = 0;
const strict = self.$__.strictMode;
const docSchema = self.$__schema;
while (index < len) {
_init(index++);
}
function _init(index) {
i = keys[index];
path = prefix + i;
schemaType = docSchema.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 (docSchema.$isRootDiscriminator && !self.$__isSelected(path)) {
return;
}
if (!schemaType && utils.isPOJO(obj[i])) {
// assume nested object
if (!doc[i]) {
doc[i] = {};
if (!strict && !(i in docSchema.tree) && !(i in docSchema.methods) && !(i in docSchema.virtuals)) {
self[i] = doc[i];
}
}
init(self, obj[i], doc[i], opts, path + '.');
} else if (!schemaType) {
doc[i] = obj[i];
if (!strict && !prefix) {
self[i] = obj[i];
}
} else {
// Retain order when overwriting defaults
if (doc.hasOwnProperty(i) && obj[i] !== void 0) {
delete doc[i];
}
if (obj[i] === null) {
doc[i] = schemaType._castNullish(null);
} else if (obj[i] !== undefined) {
const wasPopulated = obj[i].$__ == null ? null : obj[i].$__.wasPopulated;
if (schemaType && !wasPopulated) {
try {
if (opts && opts.setters) {
// Call applySetters with `init = false` because otherwise setters are a noop
const overrideInit = false;
doc[i] = schemaType.applySetters(obj[i], self, overrideInit);
} else {
doc[i] = schemaType.cast(obj[i], self, true);
}
} catch (e) {
self.invalidate(e.path, new ValidatorError({
path: e.path,
message: e.message,
type: 'cast',
value: e.value,
reason: e
}));
}
} else {
doc[i] = obj[i];
}
}
// mark as hydrated
if (!self.$isModified(path)) {
self.$__.activePaths.init(path);
}
}
}
}
/**
* 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] optional see [`Query.prototype.setOptions()`](https://mongoosejs.com/docs/api/query.html#query_Query-setOptions)
* @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api/query.html#query_Query-lean) and the [Mongoose lean tutorial](/docs/tutorials/lean.html).
* @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](https://mongoosejs.com/docs/guide.html#strict)
* @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set.
* @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);
const self = this;
query.pre(function queryPreUpdateOne(cb) {
self.constructor._middleware.execPre('updateOne', self, [self], cb);
});
query.post(function queryPostUpdateOne(cb) {
self.constructor._middleware.execPost('updateOne', self, [self], {}, 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](https://mongoosejs.com/docs/api/model.html#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 = [...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) {
if (this.$__.session != null && this.$__.session.hasEnded) {
this.$__.session = null;
return null;
}
return this.$__.session;
}
if (session != null && session.hasEnded) {
throw new MongooseError('Cannot set a document\'s session to a session that has ended. Make sure you haven\'t ' +
'called `endSession()` on the session you are passing to `$session()`.');
}
if (session == null && this.$__.session == null) {
return;
}
this.$__.session = session;
if (!this.$isSubdocument) {
const subdocs = this.$getAllSubdocs();
for (const child of subdocs) {
child.$session(session);
}
}
return session;
};
/**
* Getter/setter around whether this document will apply timestamps by
* default when using `save()` and `bulkSave()`.
*
* #### Example:
*
* const TestModel = mongoose.model('Test', new Schema({ name: String }, { timestamps: true }));
* const doc = new TestModel({ name: 'John Smith' });
*
* doc.$timestamps(); // true
*
* doc.$timestamps(false);
* await doc.save(); // Does **not** apply timestamps
*
* @param {Boolean} [value] overwrite the current session
* @return {Document|boolean|undefined} When used as a getter (no argument), a boolean will be returned indicating the timestamps option state or if unset "undefined" will be used, otherwise will return "this"
* @method $timestamps
* @api public
* @memberOf Document
*/
Document.prototype.$timestamps = function $timestamps(value) {
if (arguments.length === 0) {
if (this.$__.timestamps != null) {
return this.$__.timestamps;
}
if (this.$__schema) {
return this.$__schema.options.timestamps;
}
return undefined;
}
const currentValue = this.$timestamps();
if (value !== currentValue) {
this.$__.timestamps = value;
}
return this;
};
/**
* Overwrite all values in this document with the values of `obj`, except
* for immutable properties. Behaves similarly to `set()`, except for it
* unsets all properties that aren't in `obj`.
*
* @param {Object} obj the object to overwrite this document with
* @method overwrite
* @memberOf Document
* @instance
* @api public
* @return {Document} this
*/
Document.prototype.overwrite = function overwrite(obj) {
const keys = Array.from(new Set(Object.keys(this._doc).concat(Object.keys(obj))));
for (const key of keys) {
if (key === '_id') {
continue;
}
// Explicitly skip version key
if (this.$__schema.options.versionKey && key === this.$__schema.options.versionKey) {
continue;
}
if (this.$__schema.options.discriminatorKey && key === this.$__schema.options.discriminatorKey) {
continue;
}
this.$set(key, obj[key]);
}