forked from Automattic/mongoose
-
Notifications
You must be signed in to change notification settings - Fork 0
/
query.js
5419 lines (4847 loc) · 159 KB
/
query.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 CastError = require('./error/cast');
const DocumentNotFoundError = require('./error/notFound');
const Kareem = require('kareem');
const MongooseError = require('./error/mongooseError');
const ObjectParameterError = require('./error/objectParameter');
const QueryCursor = require('./cursor/QueryCursor');
const ValidationError = require('./error/validation');
const { applyGlobalMaxTimeMS, applyGlobalDiskUse } = require('./helpers/query/applyGlobalOption');
const handleReadPreferenceAliases = require('./helpers/query/handleReadPreferenceAliases');
const applyWriteConcern = require('./helpers/schema/applyWriteConcern');
const cast = require('./cast');
const castArrayFilters = require('./helpers/update/castArrayFilters');
const castNumber = require('./cast/number');
const castUpdate = require('./helpers/query/castUpdate');
const clone = require('./helpers/clone');
const completeMany = require('./helpers/query/completeMany');
const getDiscriminatorByValue = require('./helpers/discriminator/getDiscriminatorByValue');
const hasDollarKeys = require('./helpers/query/hasDollarKeys');
const helpers = require('./queryhelpers');
const immediate = require('./helpers/immediate');
const isExclusive = require('./helpers/projection/isExclusive');
const isInclusive = require('./helpers/projection/isInclusive');
const isSubpath = require('./helpers/projection/isSubpath');
const mpath = require('mpath');
const mquery = require('mquery');
const parseProjection = require('./helpers/projection/parseProjection');
const removeUnusedArrayFilters = require('./helpers/update/removeUnusedArrayFilters');
const sanitizeFilter = require('./helpers/query/sanitizeFilter');
const sanitizeProjection = require('./helpers/query/sanitizeProjection');
const selectPopulatedFields = require('./helpers/query/selectPopulatedFields');
const setDefaultsOnInsert = require('./helpers/setDefaultsOnInsert');
const updateValidators = require('./helpers/updateValidators');
const util = require('util');
const utils = require('./utils');
const validOps = require('./helpers/query/validOps');
const queryOptionMethods = new Set([
'allowDiskUse',
'batchSize',
'collation',
'comment',
'explain',
'hint',
'j',
'lean',
'limit',
'maxTimeMS',
'populate',
'projection',
'read',
'select',
'skip',
'slice',
'sort',
'tailable',
'w',
'writeConcern',
'wtimeout'
]);
/**
* Query constructor used for building queries. You do not need
* to instantiate a `Query` directly. Instead use Model functions like
* [`Model.find()`](/docs/api/model.html#model_Model-find).
*
* #### Example:
*
* const query = MyModel.find(); // `query` is an instance of `Query`
* query.setOptions({ lean : true });
* query.collection(MyModel.collection);
* query.where('age').gte(21).exec(callback);
*
* // You can instantiate a query directly. There is no need to do
* // this unless you're an advanced user with a very good reason to.
* const query = new mongoose.Query();
*
* @param {Object} [options]
* @param {Object} [model]
* @param {Object} [conditions]
* @param {Object} [collection] Mongoose collection
* @api public
*/
function Query(conditions, options, model, collection) {
// this stuff is for dealing with custom queries created by #toConstructor
if (!this._mongooseOptions) {
this._mongooseOptions = {};
}
options = options || {};
this._transforms = [];
this._hooks = new Kareem();
this._executionStack = null;
// this is the case where we have a CustomQuery, we need to check if we got
// options passed in, and if we did, merge them in
const keys = Object.keys(options);
for (const key of keys) {
this._mongooseOptions[key] = options[key];
}
if (collection) {
this.mongooseCollection = collection;
}
if (model) {
this.model = model;
this.schema = model.schema;
}
// this is needed because map reduce returns a model that can be queried, but
// all of the queries on said model should be lean
if (this.model && this.model._mapreduce) {
this.lean();
}
// inherit mquery
mquery.call(this, null, options);
if (collection) {
this.collection(collection);
}
if (conditions) {
this.find(conditions);
}
this.options = this.options || {};
// For gh-6880. mquery still needs to support `fields` by default for old
// versions of MongoDB
this.$useProjection = true;
const collation = this &&
this.schema &&
this.schema.options &&
this.schema.options.collation || null;
if (collation != null) {
this.options.collation = collation;
}
}
/*!
* inherit mquery
*/
Query.prototype = new mquery();
Query.prototype.constructor = Query;
Query.base = mquery.prototype;
/**
* Flag to opt out of using `$geoWithin`.
*
* ```javascript
* mongoose.Query.use$geoWithin = false;
* ```
*
* MongoDB 2.4 deprecated the use of `$within`, replacing it with `$geoWithin`. Mongoose uses `$geoWithin` by default (which is 100% backward compatible with `$within`). If you are running an older version of MongoDB, set this flag to `false` so your `within()` queries continue to work.
*
* @see geoWithin https://www.mongodb.com/docs/manual/reference/operator/geoWithin/
* @default true
* @property use$geoWithin
* @memberOf Query
* @static
* @api public
*/
Query.use$geoWithin = mquery.use$geoWithin;
/**
* Converts this query to a customized, reusable query constructor with all arguments and options retained.
*
* #### Example:
*
* // Create a query for adventure movies and read from the primary
* // node in the replica-set unless it is down, in which case we'll
* // read from a secondary node.
* const query = Movie.find({ tags: 'adventure' }).read('primaryPreferred');
*
* // create a custom Query constructor based off these settings
* const Adventure = query.toConstructor();
*
* // further narrow down our query results while still using the previous settings
* await Adventure().where({ name: /^Life/ }).exec();
*
* // since Adventure is a stand-alone constructor we can also add our own
* // helper methods and getters without impacting global queries
* Adventure.prototype.startsWith = function (prefix) {
* this.where({ name: new RegExp('^' + prefix) })
* return this;
* }
* Object.defineProperty(Adventure.prototype, 'highlyRated', {
* get: function () {
* this.where({ rating: { $gt: 4.5 }});
* return this;
* }
* })
* await Adventure().highlyRated.startsWith('Life').exec();
*
* @return {Query} subclass-of-Query
* @api public
*/
Query.prototype.toConstructor = function toConstructor() {
const model = this.model;
const coll = this.mongooseCollection;
const CustomQuery = function(criteria, options) {
if (!(this instanceof CustomQuery)) {
return new CustomQuery(criteria, options);
}
this._mongooseOptions = clone(p._mongooseOptions);
Query.call(this, criteria, options || null, model, coll);
};
util.inherits(CustomQuery, model.Query);
// set inherited defaults
const p = CustomQuery.prototype;
p.options = {};
// Need to handle `sort()` separately because entries-style `sort()` syntax
// `sort([['prop1', 1]])` confuses mquery into losing the outer nested array.
// See gh-8159
const options = Object.assign({}, this.options);
if (options.sort != null) {
p.sort(options.sort);
delete options.sort;
}
p.setOptions(options);
p.op = this.op;
p._validateOp();
p._conditions = clone(this._conditions);
p._fields = clone(this._fields);
p._update = clone(this._update, {
flattenDecimals: false
});
p._path = this._path;
p._distinct = this._distinct;
p._collection = this._collection;
p._mongooseOptions = this._mongooseOptions;
return CustomQuery;
};
/**
* Make a copy of this query so you can re-execute it.
*
* #### Example:
*
* const q = Book.findOne({ title: 'Casino Royale' });
* await q.exec();
* await q.exec(); // Throws an error because you can't execute a query twice
*
* await q.clone().exec(); // Works
*
* @method clone
* @return {Query} copy
* @memberOf Query
* @instance
* @api public
*/
Query.prototype.clone = function() {
const model = this.model;
const collection = this.mongooseCollection;
const q = new this.model.Query({}, {}, model, collection);
// Need to handle `sort()` separately because entries-style `sort()` syntax
// `sort([['prop1', 1]])` confuses mquery into losing the outer nested array.
// See gh-8159
const options = Object.assign({}, this.options);
if (options.sort != null) {
q.sort(options.sort);
delete options.sort;
}
q.setOptions(options);
q.op = this.op;
q._validateOp();
q._conditions = clone(this._conditions);
q._fields = clone(this._fields);
q._update = clone(this._update, {
flattenDecimals: false
});
q._path = this._path;
q._distinct = this._distinct;
q._collection = this._collection;
q._mongooseOptions = this._mongooseOptions;
return q;
};
/**
* Specifies a javascript function or expression to pass to MongoDBs query system.
*
* #### Example:
*
* query.$where('this.comments.length === 10 || this.name.length === 5')
*
* // or
*
* query.$where(function () {
* return this.comments.length === 10 || this.name.length === 5;
* })
*
* #### Note:
*
* Only use `$where` when you have a condition that cannot be met using other MongoDB operators like `$lt`.
* **Be sure to read about all of [its caveats](https://www.mongodb.com/docs/manual/reference/operator/where/) before using.**
*
* @see $where https://www.mongodb.com/docs/manual/reference/operator/where/
* @method $where
* @param {String|Function} js javascript string or function
* @return {Query} this
* @memberOf Query
* @instance
* @method $where
* @api public
*/
/**
* Specifies a `path` for use with chaining.
*
* #### Example:
*
* // instead of writing:
* User.find({age: {$gte: 21, $lte: 65}});
*
* // we can instead write:
* User.where('age').gte(21).lte(65);
*
* // passing query conditions is permitted
* User.find().where({ name: 'vonderful' })
*
* // chaining
* User
* .where('age').gte(21).lte(65)
* .where('name', /^vonderful/i)
* .where('friends').slice(10)
* .exec()
*
* @method where
* @memberOf Query
* @instance
* @param {String|Object} [path]
* @param {any} [val]
* @return {Query} this
* @api public
*/
/**
* Specifies a `$slice` projection for an array.
*
* #### Example:
*
* query.slice('comments', 5); // Returns the first 5 comments
* query.slice('comments', -5); // Returns the last 5 comments
* query.slice('comments', [10, 5]); // Returns the first 5 comments after the 10-th
* query.where('comments').slice(5); // Returns the first 5 comments
* query.where('comments').slice([-10, 5]); // Returns the first 5 comments after the 10-th to last
*
* **Note:** If the absolute value of the number of elements to be sliced is greater than the number of elements in the array, all array elements will be returned.
*
* // Given `arr`: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
* query.slice('arr', 20); // Returns [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
* query.slice('arr', -20); // Returns [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
*
* **Note:** If the number of elements to skip is positive and greater than the number of elements in the array, an empty array will be returned.
*
* // Given `arr`: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
* query.slice('arr', [20, 5]); // Returns []
*
* **Note:** If the number of elements to skip is negative and its absolute value is greater than the number of elements in the array, the starting position is the start of the array.
*
* // Given `arr`: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
* query.slice('arr', [-20, 5]); // Returns [1, 2, 3, 4, 5]
*
* @method slice
* @memberOf Query
* @instance
* @param {String} [path]
* @param {Number|Array} val number of elements to slice or array with number of elements to skip and number of elements to slice
* @return {Query} this
* @see mongodb https://www.mongodb.com/docs/manual/tutorial/query-documents/#projection
* @see $slice https://www.mongodb.com/docs/manual/reference/projection/slice/#prj._S_slice
* @api public
*/
Query.prototype.slice = function() {
if (arguments.length === 0) {
return this;
}
this._validate('slice');
let path;
let val;
if (arguments.length === 1) {
const arg = arguments[0];
if (typeof arg === 'object' && !Array.isArray(arg)) {
const keys = Object.keys(arg);
const numKeys = keys.length;
for (let i = 0; i < numKeys; ++i) {
this.slice(keys[i], arg[keys[i]]);
}
return this;
}
this._ensurePath('slice');
path = this._path;
val = arguments[0];
} else if (arguments.length === 2) {
if ('number' === typeof arguments[0]) {
this._ensurePath('slice');
path = this._path;
val = [arguments[0], arguments[1]];
} else {
path = arguments[0];
val = arguments[1];
}
} else if (arguments.length === 3) {
path = arguments[0];
val = [arguments[1], arguments[2]];
}
const p = {};
p[path] = { $slice: val };
this.select(p);
return this;
};
/*!
* ignore
*/
const validOpsSet = new Set(validOps);
Query.prototype._validateOp = function() {
if (this.op != null && !validOpsSet.has(this.op)) {
this.error(new Error('Query has invalid `op`: "' + this.op + '"'));
}
};
/**
* Specifies the complementary comparison value for paths specified with `where()`
*
* #### Example:
*
* User.where('age').equals(49);
*
* // is the same as
*
* User.where('age', 49);
*
* @method equals
* @memberOf Query
* @instance
* @param {Object} val
* @return {Query} this
* @api public
*/
/**
* Specifies arguments for an `$or` condition.
*
* #### Example:
*
* query.or([{ color: 'red' }, { status: 'emergency' }]);
*
* @see $or https://www.mongodb.com/docs/manual/reference/operator/or/
* @method or
* @memberOf Query
* @instance
* @param {Array} array array of conditions
* @return {Query} this
* @api public
*/
/**
* Specifies arguments for a `$nor` condition.
*
* #### Example:
*
* query.nor([{ color: 'green' }, { status: 'ok' }]);
*
* @see $nor https://www.mongodb.com/docs/manual/reference/operator/nor/
* @method nor
* @memberOf Query
* @instance
* @param {Array} array array of conditions
* @return {Query} this
* @api public
*/
/**
* Specifies arguments for a `$and` condition.
*
* #### Example:
*
* query.and([{ color: 'green' }, { status: 'ok' }])
*
* @method and
* @memberOf Query
* @instance
* @see $and https://www.mongodb.com/docs/manual/reference/operator/and/
* @param {Array} array array of conditions
* @return {Query} this
* @api public
*/
/**
* Specifies a `$gt` query condition.
*
* When called with one argument, the most recent path passed to `where()` is used.
*
* #### Example:
*
* Thing.find().where('age').gt(21);
*
* // or
* Thing.find().gt('age', 21);
*
* @method gt
* @memberOf Query
* @instance
* @param {String} [path]
* @param {Number} val
* @see $gt https://www.mongodb.com/docs/manual/reference/operator/gt/
* @api public
*/
/**
* Specifies a `$gte` query condition.
*
* When called with one argument, the most recent path passed to `where()` is used.
*
* @method gte
* @memberOf Query
* @instance
* @param {String} [path]
* @param {Number} val
* @see $gte https://www.mongodb.com/docs/manual/reference/operator/gte/
* @api public
*/
/**
* Specifies a `$lt` query condition.
*
* When called with one argument, the most recent path passed to `where()` is used.
*
* @method lt
* @memberOf Query
* @instance
* @param {String} [path]
* @param {Number} val
* @see $lt https://www.mongodb.com/docs/manual/reference/operator/lt/
* @api public
*/
/**
* Specifies a `$lte` query condition.
*
* When called with one argument, the most recent path passed to `where()` is used.
*
* @method lte
* @see $lte https://www.mongodb.com/docs/manual/reference/operator/lte/
* @memberOf Query
* @instance
* @param {String} [path]
* @param {Number} val
* @api public
*/
/**
* Specifies a `$ne` query condition.
*
* When called with one argument, the most recent path passed to `where()` is used.
*
* @see $ne https://www.mongodb.com/docs/manual/reference/operator/ne/
* @method ne
* @memberOf Query
* @instance
* @param {String} [path]
* @param {any} val
* @api public
*/
/**
* Specifies an `$in` query condition.
*
* When called with one argument, the most recent path passed to `where()` is used.
*
* @see $in https://www.mongodb.com/docs/manual/reference/operator/in/
* @method in
* @memberOf Query
* @instance
* @param {String} [path]
* @param {Array} val
* @api public
*/
/**
* Specifies an `$nin` query condition.
*
* When called with one argument, the most recent path passed to `where()` is used.
*
* @see $nin https://www.mongodb.com/docs/manual/reference/operator/nin/
* @method nin
* @memberOf Query
* @instance
* @param {String} [path]
* @param {Array} val
* @api public
*/
/**
* Specifies an `$all` query condition.
*
* When called with one argument, the most recent path passed to `where()` is used.
*
* #### Example:
*
* MyModel.find().where('pets').all(['dog', 'cat', 'ferret']);
* // Equivalent:
* MyModel.find().all('pets', ['dog', 'cat', 'ferret']);
*
* @see $all https://www.mongodb.com/docs/manual/reference/operator/all/
* @method all
* @memberOf Query
* @instance
* @param {String} [path]
* @param {Array} val
* @api public
*/
/**
* Specifies a `$size` query condition.
*
* When called with one argument, the most recent path passed to `where()` is used.
*
* #### Example:
*
* const docs = await MyModel.where('tags').size(0).exec();
* assert(Array.isArray(docs));
* console.log('documents with 0 tags', docs);
*
* @see $size https://www.mongodb.com/docs/manual/reference/operator/size/
* @method size
* @memberOf Query
* @instance
* @param {String} [path]
* @param {Number} val
* @api public
*/
/**
* Specifies a `$regex` query condition.
*
* When called with one argument, the most recent path passed to `where()` is used.
*
* @see $regex https://www.mongodb.com/docs/manual/reference/operator/regex/
* @method regex
* @memberOf Query
* @instance
* @param {String} [path]
* @param {String|RegExp} val
* @api public
*/
/**
* Specifies a `maxDistance` query condition.
*
* When called with one argument, the most recent path passed to `where()` is used.
*
* @see $maxDistance https://www.mongodb.com/docs/manual/reference/operator/maxDistance/
* @method maxDistance
* @memberOf Query
* @instance
* @param {String} [path]
* @param {Number} val
* @api public
*/
/**
* Specifies a `$mod` condition, filters documents for documents whose
* `path` property is a number that is equal to `remainder` modulo `divisor`.
*
* #### Example:
*
* // All find products whose inventory is odd
* Product.find().mod('inventory', [2, 1]);
* Product.find().where('inventory').mod([2, 1]);
* // This syntax is a little strange, but supported.
* Product.find().where('inventory').mod(2, 1);
*
* @method mod
* @memberOf Query
* @instance
* @param {String} [path]
* @param {Array} val must be of length 2, first element is `divisor`, 2nd element is `remainder`.
* @return {Query} this
* @see $mod https://www.mongodb.com/docs/manual/reference/operator/mod/
* @api public
*/
Query.prototype.mod = function() {
let val;
let path;
if (arguments.length === 1) {
this._ensurePath('mod');
val = arguments[0];
path = this._path;
} else if (arguments.length === 2 && !Array.isArray(arguments[1])) {
this._ensurePath('mod');
val = [arguments[0], arguments[1]];
path = this._path;
} else if (arguments.length === 3) {
val = [arguments[1], arguments[2]];
path = arguments[0];
} else {
val = arguments[1];
path = arguments[0];
}
const conds = this._conditions[path] || (this._conditions[path] = {});
conds.$mod = val;
return this;
};
/**
* Specifies an `$exists` condition
*
* #### Example:
*
* // { name: { $exists: true }}
* Thing.where('name').exists()
* Thing.where('name').exists(true)
* Thing.find().exists('name')
*
* // { name: { $exists: false }}
* Thing.where('name').exists(false);
* Thing.find().exists('name', false);
*
* @method exists
* @memberOf Query
* @instance
* @param {String} [path]
* @param {Boolean} val
* @return {Query} this
* @see $exists https://www.mongodb.com/docs/manual/reference/operator/exists/
* @api public
*/
/**
* Specifies an `$elemMatch` condition
*
* #### Example:
*
* query.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}})
*
* query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}})
*
* query.elemMatch('comment', function (elem) {
* elem.where('author').equals('autobot');
* elem.where('votes').gte(5);
* })
*
* query.where('comment').elemMatch(function (elem) {
* elem.where({ author: 'autobot' });
* elem.where('votes').gte(5);
* })
*
* @method elemMatch
* @memberOf Query
* @instance
* @param {String|Object|Function} path
* @param {Object|Function} filter
* @return {Query} this
* @see $elemMatch https://www.mongodb.com/docs/manual/reference/operator/elemMatch/
* @api public
*/
/**
* Defines a `$within` or `$geoWithin` argument for geo-spatial queries.
*
* #### Example:
*
* query.where(path).within().box()
* query.where(path).within().circle()
* query.where(path).within().geometry()
*
* query.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true });
* query.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] });
* query.where('loc').within({ polygon: [[],[],[],[]] });
*
* query.where('loc').within([], [], []) // polygon
* query.where('loc').within([], []) // box
* query.where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry
*
* **MUST** be used after `where()`.
*
* #### Note:
*
* As of Mongoose 3.7, `$geoWithin` is always used for queries. To change this behavior, see [Query.use$geoWithin](#query_Query-use%2524geoWithin).
*
* #### Note:
*
* In Mongoose 3.7, `within` changed from a getter to a function. If you need the old syntax, use [this](https://github.com/ebensing/mongoose-within).
*
* @method within
* @see $polygon https://www.mongodb.com/docs/manual/reference/operator/polygon/
* @see $box https://www.mongodb.com/docs/manual/reference/operator/box/
* @see $geometry https://www.mongodb.com/docs/manual/reference/operator/geometry/
* @see $center https://www.mongodb.com/docs/manual/reference/operator/center/
* @see $centerSphere https://www.mongodb.com/docs/manual/reference/operator/centerSphere/
* @memberOf Query
* @instance
* @return {Query} this
* @api public
*/
/**
* Specifies the maximum number of documents the query will return.
*
* #### Example:
*
* query.limit(20);
*
* #### Note:
*
* Cannot be used with `distinct()`
*
* @method limit
* @memberOf Query
* @instance
* @param {Number} val
* @api public
*/
Query.prototype.limit = function limit(v) {
this._validate('limit');
if (typeof v === 'string') {
try {
v = castNumber(v);
} catch (err) {
throw new CastError('Number', v, 'limit');
}
}
this.options.limit = v;
return this;
};
/**
* Specifies the number of documents to skip.
*
* #### Example:
*
* query.skip(100).limit(20);
*
* #### Note:
*
* Cannot be used with `distinct()`
*
* @method skip
* @memberOf Query
* @instance
* @param {Number} val
* @see cursor.skip https://www.mongodb.com/docs/manual/reference/method/cursor.skip/
* @api public
*/
Query.prototype.skip = function skip(v) {
this._validate('skip');
if (typeof v === 'string') {
try {
v = castNumber(v);
} catch (err) {
throw new CastError('Number', v, 'skip');
}
}
this.options.skip = v;
return this;
};
/**
* Specifies the batchSize option.
*
* #### Example:
*
* query.batchSize(100)
*
* #### Note:
*
* Cannot be used with `distinct()`
*
* @method batchSize
* @memberOf Query
* @instance
* @param {Number} val
* @see batchSize https://www.mongodb.com/docs/manual/reference/method/cursor.batchSize/
* @api public
*/
/**
* Specifies the `comment` option.
*
* #### Example:
*
* query.comment('login query')
*
* #### Note:
*
* Cannot be used with `distinct()`
*
* @method comment
* @memberOf Query
* @instance
* @param {String} val
* @see comment https://www.mongodb.com/docs/manual/reference/operator/comment/
* @api public
*/
/**
* Sets query hints.
*
* #### Example:
*
* query.hint({ indexA: 1, indexB: -1 });
*
* #### Note:
*
* Cannot be used with `distinct()`
*
* @method hint
* @memberOf Query
* @instance
* @param {Object} val a hint object
* @return {Query} this
* @see $hint https://www.mongodb.com/docs/manual/reference/operator/hint/
* @api public
*/
/**
* Get/set the current projection (AKA fields). Pass `null` to remove the
* current projection.
*
* Unlike `projection()`, the `select()` function modifies the current
* projection in place. This function overwrites the existing projection.
*
* #### Example:
*
* const q = Model.find();
* q.projection(); // null
*
* q.select('a b');
* q.projection(); // { a: 1, b: 1 }
*
* q.projection({ c: 1 });
* q.projection(); // { c: 1 }
*
* q.projection(null);
* q.projection(); // null
*
*
* @method projection
* @memberOf Query
* @instance
* @param {Object|null} arg
* @return {Object} the current projection
* @api public
*/
Query.prototype.projection = function(arg) {
if (arguments.length === 0) {
return this._fields;
}
this._fields = {};
this._userProvidedFields = {};
this.select(arg);
return this._fields;
};
/**
* Specifies which document fields to include or exclude (also known as the query "projection")