-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
model.js
4948 lines (4382 loc) · 178 KB
/
model.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 Aggregate = require('./aggregate');
const ChangeStream = require('./cursor/changeStream');
const Document = require('./document');
const DocumentNotFoundError = require('./error/notFound');
const EventEmitter = require('events').EventEmitter;
const Kareem = require('kareem');
const { MongoBulkWriteError } = require('mongodb');
const MongooseBulkWriteError = require('./error/bulkWriteError');
const MongooseError = require('./error/index');
const ObjectParameterError = require('./error/objectParameter');
const OverwriteModelError = require('./error/overwriteModel');
const Query = require('./query');
const SaveOptions = require('./options/saveOptions');
const Schema = require('./schema');
const ValidationError = require('./error/validation');
const VersionError = require('./error/version');
const ParallelSaveError = require('./error/parallelSave');
const applyDefaultsHelper = require('./helpers/document/applyDefaults');
const applyDefaultsToPOJO = require('./helpers/model/applyDefaultsToPOJO');
const applyEmbeddedDiscriminators = require('./helpers/discriminator/applyEmbeddedDiscriminators');
const applyHooks = require('./helpers/model/applyHooks');
const applyMethods = require('./helpers/model/applyMethods');
const applyProjection = require('./helpers/projection/applyProjection');
const applyReadConcern = require('./helpers/schema/applyReadConcern');
const applySchemaCollation = require('./helpers/indexes/applySchemaCollation');
const applyStaticHooks = require('./helpers/model/applyStaticHooks');
const applyStatics = require('./helpers/model/applyStatics');
const applyTimestampsHelper = require('./helpers/document/applyTimestamps');
const applyWriteConcern = require('./helpers/schema/applyWriteConcern');
const applyVirtualsHelper = require('./helpers/document/applyVirtuals');
const assignVals = require('./helpers/populate/assignVals');
const castBulkWrite = require('./helpers/model/castBulkWrite');
const clone = require('./helpers/clone');
const createPopulateQueryFilter = require('./helpers/populate/createPopulateQueryFilter');
const decorateUpdateWithVersionKey = require('./helpers/update/decorateUpdateWithVersionKey');
const getDefaultBulkwriteResult = require('./helpers/getDefaultBulkwriteResult');
const getSchemaDiscriminatorByValue = require('./helpers/discriminator/getSchemaDiscriminatorByValue');
const discriminator = require('./helpers/model/discriminator');
const each = require('./helpers/each');
const get = require('./helpers/get');
const getConstructorName = require('./helpers/getConstructorName');
const getDiscriminatorByValue = require('./helpers/discriminator/getDiscriminatorByValue');
const getModelsMapForPopulate = require('./helpers/populate/getModelsMapForPopulate');
const immediate = require('./helpers/immediate');
const internalToObjectOptions = require('./options').internalToObjectOptions;
const isDefaultIdIndex = require('./helpers/indexes/isDefaultIdIndex');
const isIndexEqual = require('./helpers/indexes/isIndexEqual');
const isTimeseriesIndex = require('./helpers/indexes/isTimeseriesIndex');
const {
getRelatedDBIndexes,
getRelatedSchemaIndexes
} = require('./helpers/indexes/getRelatedIndexes');
const decorateDiscriminatorIndexOptions = require('./helpers/indexes/decorateDiscriminatorIndexOptions');
const isPathSelectedInclusive = require('./helpers/projection/isPathSelectedInclusive');
const leanPopulateMap = require('./helpers/populate/leanPopulateMap');
const parallelLimit = require('./helpers/parallelLimit');
const prepareDiscriminatorPipeline = require('./helpers/aggregate/prepareDiscriminatorPipeline');
const pushNestedArrayPaths = require('./helpers/model/pushNestedArrayPaths');
const removeDeselectedForeignField = require('./helpers/populate/removeDeselectedForeignField');
const setDottedPath = require('./helpers/path/setDottedPath');
const STATES = require('./connectionState');
const util = require('util');
const utils = require('./utils');
const minimize = require('./helpers/minimize');
const MongooseBulkSaveIncompleteError = require('./error/bulkSaveIncompleteError');
const modelCollectionSymbol = Symbol('mongoose#Model#collection');
const modelDbSymbol = Symbol('mongoose#Model#db');
const modelSymbol = require('./helpers/symbols').modelSymbol;
const subclassedSymbol = Symbol('mongoose#Model#subclassed');
const { VERSION_INC, VERSION_WHERE, VERSION_ALL } = Document;
const saveToObjectOptions = Object.assign({}, internalToObjectOptions, {
bson: true
});
/**
* A Model is a class that's your primary tool for interacting with MongoDB.
* An instance of a Model is called a [Document](https://mongoosejs.com/docs/api/document.html#Document).
*
* In Mongoose, the term "Model" refers to subclasses of the `mongoose.Model`
* class. You should not use the `mongoose.Model` class directly. The
* [`mongoose.model()`](https://mongoosejs.com/docs/api/mongoose.html#Mongoose.prototype.model()) and
* [`connection.model()`](https://mongoosejs.com/docs/api/connection.html#Connection.prototype.model()) functions
* create subclasses of `mongoose.Model` as shown below.
*
* #### Example:
*
* // `UserModel` is a "Model", a subclass of `mongoose.Model`.
* const UserModel = mongoose.model('User', new Schema({ name: String }));
*
* // You can use a Model to create new documents using `new`:
* const userDoc = new UserModel({ name: 'Foo' });
* await userDoc.save();
*
* // You also use a model to create queries:
* const userFromDb = await UserModel.findOne({ name: 'Foo' });
*
* @param {Object} doc values for initial set
* @param {Object} [fields] optional object containing the fields that were selected in the query which returned this document. You do **not** need to set this parameter to ensure Mongoose handles your [query projection](https://mongoosejs.com/docs/api/query.html#Query.prototype.select()).
* @param {Boolean} [skipId=false] optional boolean. If true, mongoose doesn't add an `_id` field to the document.
* @inherits Document https://mongoosejs.com/docs/api/document.html
* @event `error`: If listening to this event, 'error' is emitted when a document was saved and an `error` occurred. If not listening, the event bubbles to the connection used to create this Model.
* @event `index`: Emitted after `Model#ensureIndexes` completes. If an error occurred it is passed with the event.
* @event `index-single-start`: Emitted when an individual index starts within `Model#ensureIndexes`. The fields and options being used to build the index are also passed with the event.
* @event `index-single-done`: Emitted when an individual index finishes within `Model#ensureIndexes`. If an error occurred it is passed with the event. The fields, options, and index name are also passed.
* @api public
*/
function Model(doc, fields, skipId) {
if (fields instanceof Schema) {
throw new TypeError('2nd argument to `Model` constructor must be a POJO or string, ' +
'**not** a schema. Make sure you\'re calling `mongoose.model()`, not ' +
'`mongoose.Model()`.');
}
if (typeof doc === 'string') {
throw new TypeError('First argument to `Model` constructor must be an object, ' +
'**not** a string. Make sure you\'re calling `mongoose.model()`, not ' +
'`mongoose.Model()`.');
}
Document.call(this, doc, fields, skipId);
}
/**
* Inherits from Document.
*
* All Model.prototype features are available on
* top level (non-sub) documents.
* @api private
*/
Object.setPrototypeOf(Model.prototype, Document.prototype);
Model.prototype.$isMongooseModelPrototype = true;
/**
* Connection the model uses.
*
* @api public
* @property db
* @memberOf Model
* @instance
*/
Model.prototype.db;
/**
* The collection instance this model uses.
* A Mongoose collection is a thin wrapper around a [MongoDB Node.js driver collection]([MongoDB Node.js driver collection](https://mongodb.github.io/node-mongodb-native/Next/classes/Collection.html)).
* Using `Model.collection` means you bypass Mongoose middleware, validation, and casting.
*
* This property is read-only. Modifying this property is a no-op.
*
* @api public
* @property collection
* @memberOf Model
* @instance
*/
Model.prototype.collection;
/**
* Internal collection the model uses.
*
* This property is read-only. Modifying this property is a no-op.
*
* @api private
* @property collection
* @memberOf Model
* @instance
*/
Model.prototype.$__collection;
/**
* The name of the model
*
* @api public
* @property modelName
* @memberOf Model
* @instance
*/
Model.prototype.modelName;
/**
* Additional properties to attach to the query when calling `save()` and
* `isNew` is false.
*
* @api public
* @property $where
* @memberOf Model
* @instance
*/
Model.prototype.$where;
/**
* If this is a discriminator model, `baseModelName` is the name of
* the base model.
*
* @api public
* @property baseModelName
* @memberOf Model
* @instance
*/
Model.prototype.baseModelName;
/**
* Event emitter that reports any errors that occurred. Useful for global error
* handling.
*
* #### Example:
*
* MyModel.events.on('error', err => console.log(err.message));
*
* // Prints a 'CastError' because of the above handler
* await MyModel.findOne({ _id: 'Not a valid ObjectId' }).catch(noop);
*
* @api public
* @property events
* @fires error whenever any query or model function errors
* @memberOf Model
* @static
*/
Model.events;
/**
* Compiled middleware for this model. Set in `applyHooks()`.
*
* @api private
* @property _middleware
* @memberOf Model
* @static
*/
Model._middleware;
/*!
* ignore
*/
function _applyCustomWhere(doc, where) {
if (doc.$where == null) {
return;
}
for (const key of Object.keys(doc.$where)) {
where[key] = doc.$where[key];
}
}
/*!
* ignore
*/
Model.prototype.$__handleSave = function(options, callback) {
const saveOptions = {};
applyWriteConcern(this.$__schema, options);
if (typeof options.writeConcern !== 'undefined') {
saveOptions.writeConcern = {};
if ('w' in options.writeConcern) {
saveOptions.writeConcern.w = options.writeConcern.w;
}
if ('j' in options.writeConcern) {
saveOptions.writeConcern.j = options.writeConcern.j;
}
if ('wtimeout' in options.writeConcern) {
saveOptions.writeConcern.wtimeout = options.writeConcern.wtimeout;
}
} else {
if ('w' in options) {
saveOptions.w = options.w;
}
if ('j' in options) {
saveOptions.j = options.j;
}
if ('wtimeout' in options) {
saveOptions.wtimeout = options.wtimeout;
}
}
if ('checkKeys' in options) {
saveOptions.checkKeys = options.checkKeys;
}
const session = this.$session();
const asyncLocalStorage = this[modelDbSymbol].base.transactionAsyncLocalStorage?.getStore();
if (session != null) {
saveOptions.session = session;
} else if (!options.hasOwnProperty('session') && asyncLocalStorage?.session != null) {
// Only set session from asyncLocalStorage if `session` option wasn't originally passed in options
saveOptions.session = asyncLocalStorage.session;
}
if (this.$isNew) {
// send entire doc
const obj = this.toObject(saveToObjectOptions);
if ((obj || {})._id === void 0) {
// documents must have an _id else mongoose won't know
// what to update later if more changes are made. the user
// wouldn't know what _id was generated by mongodb either
// nor would the ObjectId generated by mongodb necessarily
// match the schema definition.
immediate(function() {
callback(new MongooseError('document must have an _id before saving'));
});
return;
}
this.$__version(true, obj);
this[modelCollectionSymbol].insertOne(obj, saveOptions).then(
ret => callback(null, ret),
err => {
_setIsNew(this, true);
callback(err, null);
}
);
this.$__reset();
_setIsNew(this, false);
// Make it possible to retry the insert
this.$__.inserting = true;
return;
}
// Make sure we don't treat it as a new object on error,
// since it already exists
this.$__.inserting = false;
const delta = this.$__delta();
if (options.pathsToSave) {
for (const key in delta[1]['$set']) {
if (options.pathsToSave.includes(key)) {
continue;
} else if (options.pathsToSave.some(pathToSave => key.slice(0, pathToSave.length) === pathToSave && key.charAt(pathToSave.length) === '.')) {
continue;
} else {
delete delta[1]['$set'][key];
}
}
}
if (delta) {
if (delta instanceof MongooseError) {
callback(delta);
return;
}
const where = this.$__where(delta[0]);
if (where instanceof MongooseError) {
callback(where);
return;
}
_applyCustomWhere(this, where);
const update = delta[1];
if (this.$__schema.options.minimize) {
for (const updateOp of Object.values(update)) {
if (updateOp == null) {
continue;
}
for (const key of Object.keys(updateOp)) {
if (updateOp[key] == null || typeof updateOp[key] !== 'object') {
continue;
}
if (!utils.isPOJO(updateOp[key])) {
continue;
}
minimize(updateOp[key]);
if (Object.keys(updateOp[key]).length === 0) {
delete updateOp[key];
update.$unset = update.$unset || {};
update.$unset[key] = 1;
}
}
}
}
this[modelCollectionSymbol].updateOne(where, update, saveOptions).then(
ret => {
ret.$where = where;
callback(null, ret);
},
err => {
this.$__undoReset();
callback(err);
}
);
} else {
handleEmptyUpdate.call(this);
return;
}
// store the modified paths before the document is reset
this.$__.modifiedPaths = this.modifiedPaths();
this.$__reset();
_setIsNew(this, false);
function handleEmptyUpdate() {
const optionsWithCustomValues = Object.assign({}, options, saveOptions);
const where = this.$__where();
const optimisticConcurrency = this.$__schema.options.optimisticConcurrency;
if (optimisticConcurrency && !Array.isArray(optimisticConcurrency)) {
const key = this.$__schema.options.versionKey;
const val = this.$__getValue(key);
if (val != null) {
where[key] = val;
}
}
applyReadConcern(this.$__schema, optionsWithCustomValues);
this.constructor.collection.findOne(where, optionsWithCustomValues)
.then(documentExists => {
const matchedCount = !documentExists ? 0 : 1;
callback(null, { $where: where, matchedCount });
})
.catch(callback);
}
};
/*!
* ignore
*/
Model.prototype.$__save = function(options, callback) {
this.$__handleSave(options, (error, result) => {
if (error) {
error = this.$__schema._transformDuplicateKeyError(error);
const hooks = this.$__schema.s.hooks;
return hooks.execPost('save:error', this, [this], { error: error }, (error) => {
callback(error, this);
});
}
let numAffected = 0;
const writeConcern = options != null ?
options.writeConcern != null ?
options.writeConcern.w :
options.w :
0;
if (writeConcern !== 0) {
// Skip checking if write succeeded if writeConcern is set to
// unacknowledged writes, because otherwise `numAffected` will always be 0
if (result != null) {
if (Array.isArray(result)) {
numAffected = result.length;
} else if (result.matchedCount != null) {
numAffected = result.matchedCount;
} else {
numAffected = result;
}
}
const versionBump = this.$__.version;
// was this an update that required a version bump?
if (versionBump && !this.$__.inserting) {
const doIncrement = VERSION_INC === (VERSION_INC & this.$__.version);
this.$__.version = undefined;
const key = this.$__schema.options.versionKey;
const version = this.$__getValue(key) || 0;
if (numAffected <= 0) {
// the update failed. pass an error back
this.$__undoReset();
const err = this.$__.$versionError ||
new VersionError(this, version, this.$__.modifiedPaths);
return callback(err);
}
// increment version if was successful
if (doIncrement) {
this.$__setValue(key, version + 1);
}
}
if (result != null && numAffected <= 0) {
this.$__undoReset();
error = new DocumentNotFoundError(result.$where,
this.constructor.modelName, numAffected, result);
const hooks = this.$__schema.s.hooks;
return hooks.execPost('save:error', this, [this], { error: error }, (error) => {
callback(error, this);
});
}
}
this.$__.saving = undefined;
this.$__.savedState = {};
this.$emit('save', this, numAffected);
this.constructor.emit('save', this, numAffected);
callback(null, this);
});
};
/*!
* ignore
*/
function generateVersionError(doc, modifiedPaths) {
const key = doc.$__schema.options.versionKey;
if (!key) {
return null;
}
const version = doc.$__getValue(key) || 0;
return new VersionError(doc, version, modifiedPaths);
}
/**
* Saves this document by inserting a new document into the database if [document.isNew](https://mongoosejs.com/docs/api/document.html#Document.prototype.isNew) is `true`,
* or sends an [updateOne](https://mongoosejs.com/docs/api/document.html#Document.prototype.updateOne()) operation with just the modified paths if `isNew` is `false`.
*
* #### Example:
*
* product.sold = Date.now();
* product = await product.save();
*
* If save is successful, the returned promise will fulfill with the document
* saved.
*
* #### Example:
*
* const newProduct = await product.save();
* newProduct === product; // true
*
* @param {Object} [options] options optional options
* @param {Session} [options.session=null] the [session](https://www.mongodb.com/docs/manual/reference/server-sessions/) associated with this save operation. If not specified, defaults to the [document's associated session](https://mongoosejs.com/docs/api/document.html#Document.prototype.session()).
* @param {Object} [options.safe] (DEPRECATED) overrides [schema's safe option](https://mongoosejs.com/docs/guide.html#safe). Use the `w` option instead.
* @param {Boolean} [options.validateBeforeSave] set to false to save without validating.
* @param {Boolean} [options.validateModifiedOnly=false] if `true`, Mongoose will only validate modified paths, as opposed to modified paths and `required` paths.
* @param {Number|String} [options.w] set the [write concern](https://www.mongodb.com/docs/manual/reference/write-concern/#w-option). Overrides the [schema-level `writeConcern` option](https://mongoosejs.com/docs/guide.html#writeConcern)
* @param {Boolean} [options.j] set to true for MongoDB to wait until this `save()` has been [journaled before resolving the returned promise](https://www.mongodb.com/docs/manual/reference/write-concern/#j-option). Overrides the [schema-level `writeConcern` option](https://mongoosejs.com/docs/guide.html#writeConcern)
* @param {Number} [options.wtimeout] sets a [timeout for the write concern](https://www.mongodb.com/docs/manual/reference/write-concern/#wtimeout). Overrides the [schema-level `writeConcern` option](https://mongoosejs.com/docs/guide.html#writeConcern).
* @param {Boolean} [options.checkKeys=true] the MongoDB driver prevents you from saving keys that start with '$' or contain '.' by default. Set this option to `false` to skip that check. See [restrictions on field names](https://docs.mongodb.com/manual/reference/limits/#mongodb-limit-Restrictions-on-Field-Names)
* @param {Boolean} [options.timestamps=true] if `false` and [timestamps](https://mongoosejs.com/docs/guide.html#timestamps) are enabled, skip timestamps for this `save()`.
* @param {Array} [options.pathsToSave] An array of paths that tell mongoose to only validate and save the paths in `pathsToSave`.
* @throws {DocumentNotFoundError} if this [save updates an existing document](https://mongoosejs.com/docs/api/document.html#Document.prototype.isNew) but the document doesn't exist in the database. For example, you will get this error if the document is [deleted between when you retrieved the document and when you saved it](documents.html#updating).
* @return {Promise}
* @api public
* @see middleware https://mongoosejs.com/docs/middleware.html
*/
Model.prototype.save = async function save(options) {
if (typeof options === 'function' || typeof arguments[1] === 'function') {
throw new MongooseError('Model.prototype.save() no longer accepts a callback');
}
let parallelSave;
this.$op = 'save';
if (this.$__.saving) {
parallelSave = new ParallelSaveError(this);
} else {
this.$__.saving = new ParallelSaveError(this);
}
options = new SaveOptions(options);
if (options.hasOwnProperty('session')) {
this.$session(options.session);
}
if (this.$__.timestamps != null) {
options.timestamps = this.$__.timestamps;
}
this.$__.$versionError = generateVersionError(this, this.modifiedPaths());
if (parallelSave) {
this.$__handleReject(parallelSave);
throw parallelSave;
}
this.$__.saveOptions = options;
await new Promise((resolve, reject) => {
this.$__save(options, error => {
this.$__.saving = null;
this.$__.saveOptions = null;
this.$__.$versionError = null;
this.$op = null;
if (error != null) {
this.$__handleReject(error);
return reject(error);
}
resolve();
});
});
return this;
};
Model.prototype.$save = Model.prototype.save;
/**
* Appends versioning to the where and update clauses.
*
* @api private
* @method $__version
* @memberOf Model
* @instance
*/
Model.prototype.$__version = function(where, delta) {
const key = this.$__schema.options.versionKey;
if (where === true) {
// this is an insert
if (key) {
setDottedPath(delta, key, 0);
this.$__setValue(key, 0);
}
return;
}
if (key === false) {
return;
}
// updates
// only apply versioning if our versionKey was selected. else
// there is no way to select the correct version. we could fail
// fast here and force them to include the versionKey but
// thats a bit intrusive. can we do this automatically?
if (!this.$__isSelected(key)) {
return;
}
// $push $addToSet don't need the where clause set
if (VERSION_WHERE === (VERSION_WHERE & this.$__.version)) {
const value = this.$__getValue(key);
if (value != null) where[key] = value;
}
if (VERSION_INC === (VERSION_INC & this.$__.version)) {
if (get(delta.$set, key, null) != null) {
// Version key is getting set, means we'll increment the doc's version
// after a successful save, so we should set the incremented version so
// future saves don't fail (gh-5779)
++delta.$set[key];
} else {
delta.$inc = delta.$inc || {};
delta.$inc[key] = 1;
}
}
};
/**
* Signal that we desire an increment of this documents version.
*
* #### Example:
*
* const doc = await Model.findById(id);
* doc.increment();
* await doc.save();
*
* @see versionKeys https://mongoosejs.com/docs/guide.html#versionKey
* @memberOf Model
* @method increment
* @api public
*/
Model.prototype.increment = function increment() {
this.$__.version = VERSION_ALL;
return this;
};
/**
* Returns a query object
*
* @api private
* @method $__where
* @memberOf Model
* @instance
*/
Model.prototype.$__where = function _where(where) {
where || (where = {});
if (!where._id) {
where._id = this._doc._id;
}
if (this._doc._id === void 0) {
return new MongooseError('No _id found on document!');
}
return where;
};
/**
* Delete this document from the db. Returns a Query instance containing a `deleteOne` operation by this document's `_id`.
*
* #### Example:
*
* await product.deleteOne();
* await Product.findById(product._id); // null
*
* Since `deleteOne()` returns a Query, the `deleteOne()` will **not** execute unless you use either `await`, `.then()`, `.catch()`, or [`.exec()`](https://mongoosejs.com/docs/api/query.html#Query.prototype.exec())
*
* #### Example:
*
* product.deleteOne(); // Doesn't do anything
* product.deleteOne().exec(); // Deletes the document, returns a promise
*
* @return {Query} Query
* @api public
*/
Model.prototype.deleteOne = function deleteOne(options) {
if (typeof options === 'function' ||
typeof arguments[1] === 'function') {
throw new MongooseError('Model.prototype.deleteOne() no longer accepts a callback');
}
if (!options) {
options = {};
}
if (options.hasOwnProperty('session')) {
this.$session(options.session);
}
const self = this;
const where = this.$__where();
if (where instanceof Error) {
throw where;
}
const query = self.constructor.deleteOne(where, options);
if (this.$session() != null) {
if (!('session' in query.options)) {
query.options.session = this.$session();
}
}
query.pre(function queryPreDeleteOne(cb) {
self.constructor._middleware.execPre('deleteOne', self, [self], cb);
});
query.pre(function callSubdocPreHooks(cb) {
each(self.$getAllSubdocs(), (subdoc, cb) => {
subdoc.constructor._middleware.execPre('deleteOne', subdoc, [subdoc], cb);
}, cb);
});
query.pre(function skipIfAlreadyDeleted(cb) {
if (self.$__.isDeleted) {
return cb(Kareem.skipWrappedFunction());
}
return cb();
});
query.post(function callSubdocPostHooks(cb) {
each(self.$getAllSubdocs(), (subdoc, cb) => {
subdoc.constructor._middleware.execPost('deleteOne', subdoc, [subdoc], {}, cb);
}, cb);
});
query.post(function queryPostDeleteOne(cb) {
self.constructor._middleware.execPost('deleteOne', self, [self], {}, cb);
});
return query;
};
/**
* Returns the model instance used to create this document if no `name` specified.
* If `name` specified, returns the model with the given `name`.
*
* #### Example:
*
* const doc = new Tank({});
* doc.$model() === Tank; // true
* await doc.$model('User').findById(id);
*
* @param {String} [name] model name
* @method $model
* @api public
* @return {Model}
*/
Model.prototype.$model = function $model(name) {
if (arguments.length === 0) {
return this.constructor;
}
return this[modelDbSymbol].model(name);
};
/**
* Returns the model instance used to create this document if no `name` specified.
* If `name` specified, returns the model with the given `name`.
*
* #### Example:
*
* const doc = new Tank({});
* doc.$model() === Tank; // true
* await doc.$model('User').findById(id);
*
* @param {String} [name] model name
* @method model
* @api public
* @return {Model}
*/
Model.prototype.model = Model.prototype.$model;
/**
* Returns a document with `_id` only if at least one document exists in the database that matches
* the given `filter`, and `null` otherwise.
*
* Under the hood, `MyModel.exists({ answer: 42 })` is equivalent to
* `MyModel.findOne({ answer: 42 }).select({ _id: 1 }).lean()`
*
* #### Example:
*
* await Character.deleteMany({});
* await Character.create({ name: 'Jean-Luc Picard' });
*
* await Character.exists({ name: /picard/i }); // { _id: ... }
* await Character.exists({ name: /riker/i }); // null
*
* This function triggers the following middleware.
*
* - `findOne()`
*
* @param {Object} filter
* @param {Object} [options] optional see [`Query.prototype.setOptions()`](https://mongoosejs.com/docs/api/query.html#Query.prototype.setOptions())
* @return {Query}
*/
Model.exists = function exists(filter, options) {
_checkContext(this, 'exists');
if (typeof arguments[2] === 'function') {
throw new MongooseError('Model.exists() no longer accepts a callback');
}
const query = this.findOne(filter).
select({ _id: 1 }).
lean().
setOptions(options);
return query;
};
/**
* Adds a discriminator type.
*
* #### Example:
*
* function BaseSchema() {
* Schema.apply(this, arguments);
*
* this.add({
* name: String,
* createdAt: Date
* });
* }
* util.inherits(BaseSchema, Schema);
*
* const PersonSchema = new BaseSchema();
* const BossSchema = new BaseSchema({ department: String });
*
* const Person = mongoose.model('Person', PersonSchema);
* const Boss = Person.discriminator('Boss', BossSchema);
* new Boss().__t; // "Boss". `__t` is the default `discriminatorKey`
*
* const employeeSchema = new Schema({ boss: ObjectId });
* const Employee = Person.discriminator('Employee', employeeSchema, 'staff');
* new Employee().__t; // "staff" because of 3rd argument above
*
* @param {String} name discriminator model name
* @param {Schema} schema discriminator model schema
* @param {Object|String} [options] If string, same as `options.value`.
* @param {String} [options.value] the string stored in the `discriminatorKey` property. If not specified, Mongoose uses the `name` parameter.
* @param {Boolean} [options.clone=true] By default, `discriminator()` clones the given `schema`. Set to `false` to skip cloning.
* @param {Boolean} [options.overwriteModels=false] by default, Mongoose does not allow you to define a discriminator with the same name as another discriminator. Set this to allow overwriting discriminators with the same name.
* @param {Boolean} [options.mergeHooks=true] By default, Mongoose merges the base schema's hooks with the discriminator schema's hooks. Set this option to `false` to make Mongoose use the discriminator schema's hooks instead.
* @param {Boolean} [options.mergePlugins=true] By default, Mongoose merges the base schema's plugins with the discriminator schema's plugins. Set this option to `false` to make Mongoose use the discriminator schema's plugins instead.
* @return {Model} The newly created discriminator model
* @api public
*/
Model.discriminator = function(name, schema, options) {
let model;
if (typeof name === 'function') {
model = name;
name = utils.getFunctionName(model);
if (!(model.prototype instanceof Model)) {
throw new MongooseError('The provided class ' + name + ' must extend Model');
}
}
options = options || {};
const value = utils.isPOJO(options) ? options.value : options;
const clone = typeof options.clone === 'boolean' ? options.clone : true;
const mergePlugins = typeof options.mergePlugins === 'boolean' ? options.mergePlugins : true;
const overwriteModels = typeof options.overwriteModels === 'boolean' ? options.overwriteModels : false;
_checkContext(this, 'discriminator');
if (utils.isObject(schema) && !schema.instanceOfSchema) {
schema = new Schema(schema);
}
if (schema instanceof Schema && clone) {
schema = schema.clone();
}
schema = discriminator(this, name, schema, value, mergePlugins, options.mergeHooks, overwriteModels);
if (this.db.models[name] && !schema.options.overwriteModels && !overwriteModels) {
throw new OverwriteModelError(name);
}
schema.$isRootDiscriminator = true;
schema.$globalPluginsApplied = true;
model = this.db.model(model || name, schema, this.$__collection.name);
this.discriminators[name] = model;
const d = this.discriminators[name];
Object.setPrototypeOf(d.prototype, this.prototype);
Object.defineProperty(d, 'baseModelName', {
value: this.modelName,
configurable: true,
writable: false
});
// apply methods and statics
applyMethods(d, schema);
applyStatics(d, schema);
if (this[subclassedSymbol] != null) {
for (const submodel of this[subclassedSymbol]) {
submodel.discriminators = submodel.discriminators || {};
submodel.discriminators[name] =
model.__subclass(model.db, schema, submodel.collection.name);
}
}
return d;
};
/**
* Make sure `this` is a model
* @api private
*/
function _checkContext(ctx, fnName) {
// Check context, because it is easy to mistakenly type
// `new Model.discriminator()` and get an incomprehensible error
if (ctx == null || ctx === global) {
throw new MongooseError('`Model.' + fnName + '()` cannot run without a ' +
'model as `this`. Make sure you are calling `MyModel.' + fnName + '()` ' +
'where `MyModel` is a Mongoose model.');
} else if (ctx[modelSymbol] == null) {
throw new MongooseError('`Model.' + fnName + '()` cannot run without a ' +
'model as `this`. Make sure you are not calling ' +
'`new Model.' + fnName + '()`');
}
}
// Model (class) features
/*!
* Give the constructor the ability to emit events.
*/
for (const i in EventEmitter.prototype) {
Model[i] = EventEmitter.prototype[i];
}
/**
* This function is responsible for initializing the underlying connection in MongoDB based on schema options.
* This function performs the following operations:
*
* - `createCollection()` unless [`autoCreate`](https://mongoosejs.com/docs/guide.html#autoCreate) option is turned off
* - `ensureIndexes()` unless [`autoIndex`](https://mongoosejs.com/docs/guide.html#autoIndex) option is turned off
* - `createSearchIndex()` on all schema search indexes if `autoSearchIndex` is enabled.
*
* Mongoose calls this function automatically when a model is a created using
* [`mongoose.model()`](https://mongoosejs.com/docs/api/mongoose.html#Mongoose.prototype.model()) or
* [`connection.model()`](https://mongoosejs.com/docs/api/connection.html#Connection.prototype.model()), so you
* don't need to call `init()` to trigger index builds.
*
* However, you _may_ need to call `init()` to get back a promise that will resolve when your indexes are finished.
* Calling `await Model.init()` is helpful if you need to wait for indexes to build before continuing.
* For example, if you want to wait for unique indexes to build before continuing with a test case.
*
* #### Example:
*
* const eventSchema = new Schema({ thing: { type: 'string', unique: true } })
* // This calls `Event.init()` implicitly, so you don't need to call
* // `Event.init()` on your own.
* const Event = mongoose.model('Event', eventSchema);
*
* await Event.init();
* console.log('Indexes are done building!');
*
* @api public
* @returns {Promise}