-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
model.js
4698 lines (4185 loc) · 146 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').DocumentNotFoundError;
const DivergentArrayError = require('./error').DivergentArrayError;
const Error = require('./error');
const EventEmitter = require('events').EventEmitter;
const MongooseMap = require('./types/map');
const OverwriteModelError = require('./error').OverwriteModelError;
const PromiseProvider = require('./promise_provider');
const Query = require('./query');
const Schema = require('./schema');
const VersionError = require('./error').VersionError;
const ParallelSaveError = require('./error').ParallelSaveError;
const applyQueryMiddleware = require('./helpers/query/applyQueryMiddleware');
const applyHooks = require('./helpers/model/applyHooks');
const applyMethods = require('./helpers/model/applyMethods');
const applyStatics = require('./helpers/model/applyStatics');
const applyWriteConcern = require('./helpers/schema/applyWriteConcern');
const assignRawDocsToIdStructure = require('./helpers/populate/assignRawDocsToIdStructure');
const castBulkWrite = require('./helpers/model/castBulkWrite');
const discriminator = require('./helpers/model/discriminator');
const getDiscriminatorByValue = require('./queryhelpers').getDiscriminatorByValue;
const immediate = require('./helpers/immediate');
const internalToObjectOptions = require('./options').internalToObjectOptions;
const isPathExcluded = require('./helpers/projection/isPathExcluded');
const isPathSelectedInclusive = require('./helpers/projection/isPathSelectedInclusive');
const get = require('./helpers/get');
const getSchemaTypes = require('./helpers/populate/getSchemaTypes');
const getVirtual = require('./helpers/populate/getVirtual');
const leanPopulateMap = require('./helpers/populate/leanPopulateMap');
const modifiedPaths = require('./helpers/update/modifiedPaths');
const mpath = require('mpath');
const normalizeRefPath = require('./helpers/populate/normalizeRefPath');
const parallel = require('async/parallel');
const parallelLimit = require('async/parallelLimit');
const setParentPointers = require('./helpers/schema/setParentPointers');
const util = require('util');
const utils = require('./utils');
const VERSION_WHERE = 1;
const VERSION_INC = 2;
const VERSION_ALL = VERSION_WHERE | VERSION_INC;
const modelCollectionSymbol = Symbol.for('mongoose#Model#collection');
const modelSymbol = require('./helpers/symbols').modelSymbol;
const schemaMixedSymbol = require('./schema/symbols').schemaMixedSymbol;
/**
* A Model is a class that's your primary tool for interacting with MongoDB.
* An instance of a Model is called a [Document](./api.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()`](./api.html#mongoose_Mongoose-model) and
* [`connection.model()`](./api.html#connection_Connection-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 [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 projetion](./api.html#query_Query-select).
* @inherits Document http://mongoosejs.com/docs/api.html#document-js
* @event `error`: If listening to this event, 'error' is emitted when a document was saved without passing a callback 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` must be a POJO or string, ' +
'**not** a schema. 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.
*/
Model.prototype.__proto__ = Document.prototype;
Model.prototype.$isMongooseModelPrototype = true;
/**
* Connection the model uses.
*
* @api public
* @property db
* @memberOf Model
* @instance
*/
Model.prototype.db;
/**
* Collection the model uses.
*
* This property is read-only. Modifying this property is a no-op.
*
* @api public
* @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: 'notanid' }).catch(noop);
*
* @api public
* @fires error whenever any query or model function errors
* @memberOf Model
* @static events
*/
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;
}
const keys = Object.keys(doc.$where);
const len = keys.length;
for (let i = 0; i < len; ++i) {
where[keys[i]] = doc.$where[keys[i]];
}
}
/*!
* ignore
*/
Model.prototype.$__handleSave = function(options, callback) {
const _this = this;
let saveOptions = {};
if ('safe' in options) {
_handleSafe(options);
}
applyWriteConcern(this.schema, options);
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 = 'session' in options ? options.session : this.$session();
if (session != null) {
saveOptions.session = session;
this.$session(session);
}
if (Object.keys(saveOptions).length === 0) {
saveOptions = null;
}
if (this.isNew) {
// send entire doc
const obj = this.toObject(internalToObjectOptions);
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 my mongodb necessarily
// match the schema definition.
setTimeout(function() {
callback(new Error('document must have an _id before saving'));
}, 0);
return;
}
this.$__version(true, obj);
this[modelCollectionSymbol].insertOne(obj, saveOptions, function(err, ret) {
if (err) {
_this.isNew = true;
_this.emit('isNew', true);
_this.constructor.emit('isNew', true);
callback(err, null);
return;
}
callback(null, ret);
});
this.$__reset();
this.isNew = false;
this.emit('isNew', false);
this.constructor.emit('isNew', false);
// Make it possible to retry the insert
this.$__.inserting = true;
} else {
// 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 (delta) {
if (delta instanceof Error) {
callback(delta);
return;
}
const where = this.$__where(delta[0]);
if (where instanceof Error) {
callback(where);
return;
}
_applyCustomWhere(this, where);
this[modelCollectionSymbol].updateOne(where, delta[1], saveOptions, function(err, ret) {
if (err) {
callback(err);
return;
}
ret.$where = where;
callback(null, ret);
});
} else {
this.$__reset();
callback();
return;
}
this.emit('isNew', false);
this.constructor.emit('isNew', false);
}
};
/*!
* ignore
*/
Model.prototype.$__save = function(options, callback) {
this.$__handleSave(options, (error, result) => {
if (error) {
return this.schema.s.hooks.execPost('save:error', this, [this], { error: error }, function(error) {
callback(error);
});
}
// store the modified paths before the document is reset
const modifiedPaths = this.modifiedPaths();
this.$__reset();
let numAffected = 0;
if (get(options, 'safe.w') !== 0 && get(options, 'w') !== 0) {
// Skip checking if write succeeded if writeConcern is set to
// unacknowledged writes, because otherwise `numAffected` will always be 0
if (result) {
if (Array.isArray(result)) {
numAffected = result.length;
} else if (result.result && result.result.n !== undefined) {
numAffected = result.result.n;
} else if (result.result && result.result.nModified !== undefined) {
numAffected = result.result.nModified;
} else {
numAffected = result;
}
}
// was this an update that required a version bump?
if (this.$__.version && !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
const err = options.$versionError || new VersionError(this, version, modifiedPaths);
return callback(err);
}
// increment version if was successful
if (doIncrement) {
this.setValue(key, version + 1);
}
}
if (result != null && numAffected <= 0) {
error = new DocumentNotFoundError(result.$where);
return this.schema.s.hooks.execPost('save:error', this, [this], { error: error }, function(error) {
callback(error);
});
}
}
this.$__.saving = undefined;
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.
*
* ####Example:
*
* product.sold = Date.now();
* product.save(function (err, product) {
* if (err) ..
* })
*
* The callback will receive two parameters
*
* 1. `err` if an error occurred
* 2. `product` which is the saved `product`
*
* As an extra measure of flow control, save will return a Promise.
* ####Example:
* product.save().then(function(product) {
* ...
* });
*
* @param {Object} [options] options optional options
* @param {Object} [options.safe] (DEPRECATED) overrides [schema's safe option](http://mongoosejs.com//docs/guide.html#safe). Use the `w` option instead.
* @param {Boolean} [options.validateBeforeSave] set to false to save without validating.
* @param {Number|String} [options.w] set the [write concern](https://docs.mongodb.com/manual/reference/write-concern/#w-option). Overrides the [schema-level `writeConcern` option](/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://docs.mongodb.com/manual/reference/write-concern/#j-option). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern)
* @param {Number} [options.wtimeout] sets a [timeout for the write concern](https://docs.mongodb.com/manual/reference/write-concern/#wtimeout). Overrides the [schema-level `writeConcern` option](/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/#Restrictions-on-Field-Names)
* @param {Boolean} [options.timestamps=true] if `false` and [timestamps](./guide.html#timestamps) are enabled, skip timestamps for this `save()`.
* @param {Session} [options.session=null] the [session](https://docs.mongodb.com/manual/reference/server-sessions/) associated with this save operation. If not specified, defaults to the [document's associated session](api.html#document_Document-$session).
* @param {Function} [fn] optional callback
* @return {Promise|undefined} Returns undefined if used with callback or a Promise otherwise.
* @api public
* @see middleware http://mongoosejs.com/docs/middleware.html
*/
Model.prototype.save = function(options, fn) {
let parallelSave;
if (this.$__.saving) {
parallelSave = new ParallelSaveError(this);
} else {
this.$__.saving = new ParallelSaveError(this);
}
if (typeof options === 'function') {
fn = options;
options = undefined;
}
if (options != null) {
options = utils.clone(options);
} else {
options = {};
}
if (fn) {
fn = this.constructor.$wrapCallback(fn);
}
options.$versionError = generateVersionError(this, this.modifiedPaths());
return utils.promiseOrCallback(fn, cb => {
if (parallelSave) {
this.$__handleReject(parallelSave);
return cb(parallelSave);
}
this.$__.saveOptions = options;
this.$__save(options, error => {
this.$__.saving = undefined;
delete this.$__.saveOptions;
if (error) {
this.$__handleReject(error);
return cb(error);
}
cb(null, this);
});
}, this.constructor.events);
};
/*!
* Determines whether versioning should be skipped for the given path
*
* @param {Document} self
* @param {String} path
* @return {Boolean} true if versioning should be skipped for the given path
*/
function shouldSkipVersioning(self, path) {
const skipVersioning = self.schema.options.skipVersioning;
if (!skipVersioning) return false;
// Remove any array indexes from the path
path = path.replace(/\.\d+\./, '.');
return skipVersioning[path];
}
/*!
* Apply the operation to the delta (update) clause as
* well as track versioning for our where clause.
*
* @param {Document} self
* @param {Object} where
* @param {Object} delta
* @param {Object} data
* @param {Mixed} val
* @param {String} [operation]
*/
function operand(self, where, delta, data, val, op) {
// delta
op || (op = '$set');
if (!delta[op]) delta[op] = {};
delta[op][data.path] = val;
// disabled versioning?
if (self.schema.options.versionKey === false) return;
// path excluded from versioning?
if (shouldSkipVersioning(self, data.path)) return;
// already marked for versioning?
if (VERSION_ALL === (VERSION_ALL & self.$__.version)) return;
switch (op) {
case '$set':
case '$unset':
case '$pop':
case '$pull':
case '$pullAll':
case '$push':
case '$addToSet':
break;
default:
// nothing to do
return;
}
// ensure updates sent with positional notation are
// editing the correct array element.
// only increment the version if an array position changes.
// modifying elements of an array is ok if position does not change.
if (op === '$push' || op === '$addToSet' || op === '$pullAll' || op === '$pull') {
self.$__.version = VERSION_INC;
} else if (/^\$p/.test(op)) {
// potentially changing array positions
self.increment();
} else if (Array.isArray(val)) {
// $set an array
self.increment();
} else if (/\.\d+\.|\.\d+$/.test(data.path)) {
// now handling $set, $unset
// subpath of array
self.$__.version = VERSION_WHERE;
}
}
/*!
* Compiles an update and where clause for a `val` with _atomics.
*
* @param {Document} self
* @param {Object} where
* @param {Object} delta
* @param {Object} data
* @param {Array} value
*/
function handleAtomics(self, where, delta, data, value) {
if (delta.$set && delta.$set[data.path]) {
// $set has precedence over other atomics
return;
}
if (typeof value.$__getAtomics === 'function') {
value.$__getAtomics().forEach(function(atomic) {
const op = atomic[0];
const val = atomic[1];
operand(self, where, delta, data, val, op);
});
return;
}
// legacy support for plugins
const atomics = value._atomics;
const ops = Object.keys(atomics);
let i = ops.length;
let val;
let op;
if (i === 0) {
// $set
if (utils.isMongooseObject(value)) {
value = value.toObject({depopulate: 1, _isNested: true});
} else if (value.valueOf) {
value = value.valueOf();
}
return operand(self, where, delta, data, value);
}
function iter(mem) {
return utils.isMongooseObject(mem)
? mem.toObject({depopulate: 1, _isNested: true})
: mem;
}
while (i--) {
op = ops[i];
val = atomics[op];
if (utils.isMongooseObject(val)) {
val = val.toObject({depopulate: true, transform: false, _isNested: true});
} else if (Array.isArray(val)) {
val = val.map(iter);
} else if (val.valueOf) {
val = val.valueOf();
}
if (op === '$addToSet') {
val = {$each: val};
}
operand(self, where, delta, data, val, op);
}
}
/**
* Produces a special query document of the modified properties used in updates.
*
* @api private
* @method $__delta
* @memberOf Model
* @instance
*/
Model.prototype.$__delta = function() {
const dirty = this.$__dirty();
if (!dirty.length && VERSION_ALL !== this.$__.version) {
return;
}
const where = {};
const delta = {};
const len = dirty.length;
const divergent = [];
let d = 0;
where._id = this._doc._id;
// If `_id` is an object, need to depopulate, but also need to be careful
// because `_id` can technically be null (see gh-6406)
if (get(where, '_id.$__', null) != null) {
where._id = where._id.toObject({ transform: false, depopulate: true });
}
for (; d < len; ++d) {
const data = dirty[d];
let value = data.value;
const match = checkDivergentArray(this, data.path, value);
if (match) {
divergent.push(match);
continue;
}
const pop = this.populated(data.path, true);
if (!pop && this.$__.selected) {
// If any array was selected using an $elemMatch projection, we alter the path and where clause
// NOTE: MongoDB only supports projected $elemMatch on top level array.
const pathSplit = data.path.split('.');
const top = pathSplit[0];
if (this.$__.selected[top] && this.$__.selected[top].$elemMatch) {
// If the selected array entry was modified
if (pathSplit.length > 1 && pathSplit[1] == 0 && typeof where[top] === 'undefined') {
where[top] = this.$__.selected[top];
pathSplit[1] = '$';
data.path = pathSplit.join('.');
}
// if the selected array was modified in any other way throw an error
else {
divergent.push(data.path);
continue;
}
}
}
if (divergent.length) continue;
if (value === undefined) {
operand(this, where, delta, data, 1, '$unset');
} else if (value === null) {
operand(this, where, delta, data, null);
} else if (value._path && value._atomics) {
// arrays and other custom types (support plugins etc)
handleAtomics(this, where, delta, data, value);
} else if (value._path && Buffer.isBuffer(value)) {
// MongooseBuffer
value = value.toObject();
operand(this, where, delta, data, value);
} else {
value = utils.clone(value, {
depopulate: true,
transform: false,
virtuals: false,
_isNested: true
});
operand(this, where, delta, data, value);
}
}
if (divergent.length) {
return new DivergentArrayError(divergent);
}
if (this.$__.version) {
this.$__version(where, delta);
}
return [where, delta];
};
/*!
* Determine if array was populated with some form of filter and is now
* being updated in a manner which could overwrite data unintentionally.
*
* @see https://github.com/Automattic/mongoose/issues/1334
* @param {Document} doc
* @param {String} path
* @return {String|undefined}
*/
function checkDivergentArray(doc, path, array) {
// see if we populated this path
const pop = doc.populated(path, true);
if (!pop && doc.$__.selected) {
// If any array was selected using an $elemMatch projection, we deny the update.
// NOTE: MongoDB only supports projected $elemMatch on top level array.
const top = path.split('.')[0];
if (doc.$__.selected[top + '.$']) {
return top;
}
}
if (!(pop && array && array.isMongooseArray)) return;
// If the array was populated using options that prevented all
// documents from being returned (match, skip, limit) or they
// deselected the _id field, $pop and $set of the array are
// not safe operations. If _id was deselected, we do not know
// how to remove elements. $pop will pop off the _id from the end
// of the array in the db which is not guaranteed to be the
// same as the last element we have here. $set of the entire array
// would be similarily destructive as we never received all
// elements of the array and potentially would overwrite data.
const check = pop.options.match ||
pop.options.options && utils.object.hasOwnProperty(pop.options.options, 'limit') || // 0 is not permitted
pop.options.options && pop.options.options.skip || // 0 is permitted
pop.options.select && // deselected _id?
(pop.options.select._id === 0 ||
/\s?-_id\s?/.test(pop.options.select));
if (check) {
const atomics = array._atomics;
if (Object.keys(atomics).length === 0 || atomics.$set || atomics.$pop) {
return path;
}
}
}
/**
* 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) this.setValue(key, delta[key] = 0);
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:
*
* Model.findById(id, function (err, doc) {
* doc.increment();
* doc.save(function (err) { .. })
* })
*
* @see versionKeys http://mongoosejs.com/docs/guide.html#versionKey
* @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 Error('No _id found on document!');
}
return where;
};
/**
* Removes this document from the db.
*
* ####Example:
* product.remove(function (err, product) {
* if (err) return handleError(err);
* Product.findById(product._id, function (err, product) {
* console.log(product) // null
* })
* })
*
*
* As an extra measure of flow control, remove will return a Promise (bound to `fn` if passed) so it could be chained, or hooked to recieve errors
*
* ####Example:
* product.remove().then(function (product) {
* ...
* }).catch(function (err) {
* assert.ok(err)
* })
*
* @param {function(err,product)} [fn] optional callback
* @return {Promise} Promise
* @api public
*/
Model.prototype.remove = function remove(options, fn) {
if (typeof options === 'function') {
fn = options;
options = undefined;
}
if (!options) {
options = {};
}
if (fn) {
fn = this.constructor.$wrapCallback(fn);
}
return utils.promiseOrCallback(fn, cb => {
this.$__remove(options, cb);
}, this.constructor.events);
};
/**
* Alias for remove
*/
Model.prototype.delete = Model.prototype.remove;
/*!
* ignore
*/
Model.prototype.$__remove = function $__remove(options, cb) {
if (this.$__.isDeleted) {
return immediate(() => cb(null, this));
}
const where = this.$__where();
if (where instanceof Error) {
return cb(where);
}
_applyCustomWhere(this, where);
if (this.$session() != null) {
options = options || {};
if (!('session' in options)) {
options.session = this.$session();
}
}
this[modelCollectionSymbol].deleteOne(where, options, err => {
if (!err) {
this.$__.isDeleted = true;
this.emit('remove', this);
this.constructor.emit('remove', this);
return cb(null, this);
}
this.$__.isDeleted = false;
cb(err);
});
};
/**
* Returns another Model instance.
*
* ####Example:
*
* var doc = new Tank;
* doc.model('User').findById(id, callback);
*
* @param {String} name model name
* @api public
*/
Model.prototype.model = function model(name) {
return this.db.model(name);
};
/**
* Adds a discriminator type.
*
* ####Example:
*
* function BaseSchema() {
* Schema.apply(this, arguments);
*
* this.add({
* name: String,
* createdAt: Date
* });
* }
* util.inherits(BaseSchema, Schema);
*
* var PersonSchema = new BaseSchema();
* var BossSchema = new BaseSchema({ department: String });
*
* var Person = mongoose.model('Person', PersonSchema);
* var Boss = Person.discriminator('Boss', BossSchema);
* new Boss().__t; // "Boss". `__t` is the default `discriminatorKey`
*
* var employeeSchema = new Schema({ boss: ObjectId });
* var 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 {String} value the string stored in the `discriminatorKey` property
* @api public
*/
Model.discriminator = function(name, schema, value) {
let model;
if (typeof name === 'function') {