-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
query.js
5154 lines (4595 loc) · 150 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 ReadPreference = require('./driver').get().ReadPreference;
const applyWriteConcern = require('./helpers/schema/applyWriteConcern');
const cast = require('./cast');
const castArrayFilters = require('./helpers/update/castArrayFilters');
const castUpdate = require('./helpers/query/castUpdate');
const completeMany = require('./helpers/query/completeMany');
const get = require('./helpers/get');
const hasDollarKeys = require('./helpers/query/hasDollarKeys');
const helpers = require('./queryhelpers');
const isInclusive = require('./helpers/projection/isInclusive');
const mquery = require('mquery');
const selectPopulatedFields = require('./helpers/query/selectPopulatedFields');
const setDefaultsOnInsert = require('./helpers/setDefaultsOnInsert');
const slice = require('sliced');
const updateValidators = require('./helpers/updateValidators');
const util = require('util');
const utils = require('./utils');
const wrapThunk = require('./helpers/query/wrapThunk');
/**
* Query constructor used for building queries. You do not need
* to instantiate a `Query` directly. Instead use Model functions like
* [`Model.find()`](/docs/api.html#find_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._executionCount = 0;
// 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 (let i = 0; i < keys.length; ++i) {
const k = keys[i];
this._mongooseOptions[k] = options[k];
}
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, this.mongooseCollection, options);
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 = get(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`.
*
* 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 http://docs.mongodb.org/manual/reference/operator/geoWithin/
* @default true
* @property use$geoWithin
* @memberOf Query
* @receiver Query
* @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.
* var query = Movie.find({ tags: 'adventure' }).read('primaryPreferred');
*
* // create a custom Query constructor based off these settings
* var Adventure = query.toConstructor();
*
* // Adventure is now a subclass of mongoose.Query and works the same way but with the
* // default query parameters and options set.
* Adventure().exec(callback)
*
* // further narrow down our query results while still using the previous settings
* Adventure().where({ name: /^Life/ }).exec(callback);
*
* // 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;
* }
* })
* Adventure().highlyRated.startsWith('Life').exec(callback)
*
* @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 = utils.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 = {};
p.setOptions(this.options);
p.op = this.op;
p._conditions = utils.clone(this._conditions);
p._fields = utils.clone(this._fields);
p._update = utils.clone(this._update, {
flattenDecimals: false
});
p._path = this._path;
p._distinct = this._distinct;
p._collection = this._collection;
p._mongooseOptions = this._mongooseOptions;
return CustomQuery;
};
/**
* 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](http://docs.mongodb.org/manual/reference/operator/where/) before using.**
*
* @see $where http://docs.mongodb.org/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}}, callback);
*
* // 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(callback)
*
* @method where
* @memberOf Query
* @instance
* @param {String|Object} [path]
* @param {any} [val]
* @return {Query} this
* @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 = slice(arguments);
} else {
path = arguments[0];
val = arguments[1];
}
} else if (arguments.length === 3) {
path = arguments[0];
val = slice(arguments, 1);
}
const p = {};
p[path] = { $slice: val };
this.select(p);
return this;
};
/**
* 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 http://docs.mongodb.org/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 http://docs.mongodb.org/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 http://docs.mongodb.org/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 http://docs.mongodb.org/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 http://docs.mongodb.org/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 http://docs.mongodb.org/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 http://docs.mongodb.org/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 http://docs.mongodb.org/manual/reference/operator/ne/
* @method ne
* @memberOf Query
* @instance
* @param {String} [path]
* @param {Number} val
* @api public
*/
/**
* Specifies an `$in` query condition.
*
* When called with one argument, the most recent path passed to `where()` is used.
*
* @see $in http://docs.mongodb.org/manual/reference/operator/in/
* @method in
* @memberOf Query
* @instance
* @param {String} [path]
* @param {Number} val
* @api public
*/
/**
* Specifies an `$nin` query condition.
*
* When called with one argument, the most recent path passed to `where()` is used.
*
* @see $nin http://docs.mongodb.org/manual/reference/operator/nin/
* @method nin
* @memberOf Query
* @instance
* @param {String} [path]
* @param {Number} 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 http://docs.mongodb.org/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
*
* MyModel.where('tags').size(0).exec(function (err, docs) {
* if (err) return handleError(err);
*
* assert(Array.isArray(docs));
* console.log('documents with 0 tags', docs);
* })
*
* @see $size http://docs.mongodb.org/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 http://docs.mongodb.org/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 http://docs.mongodb.org/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 http://docs.mongodb.org/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 = slice(arguments);
path = this._path;
} else if (arguments.length === 3) {
val = slice(arguments, 1);
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 {Number} val
* @return {Query} this
* @see $exists http://docs.mongodb.org/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} criteria
* @return {Query} this
* @see $elemMatch http://docs.mongodb.org/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 http://docs.mongodb.org/manual/reference/operator/polygon/
* @see $box http://docs.mongodb.org/manual/reference/operator/box/
* @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/
* @see $center http://docs.mongodb.org/manual/reference/operator/center/
* @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/
* @memberOf Query
* @instance
* @return {Query} this
* @api public
*/
/**
* Specifies a `$slice` projection for an array.
*
* ####Example
*
* query.slice('comments', 5)
* query.slice('comments', -5)
* query.slice('comments', [10, 5])
* query.where('comments').slice(5)
* query.where('comments').slice([-10, 5])
*
* @method slice
* @memberOf Query
* @instance
* @param {String} [path]
* @param {Number} val number/range of elements to slice
* @return {Query} this
* @see mongodb http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields#RetrievingaSubsetofFields-RetrievingaSubrangeofArrayElements
* @see $slice http://docs.mongodb.org/manual/reference/projection/slice/#prj._S_slice
* @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
*/
/**
* 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 http://docs.mongodb.org/manual/reference/method/cursor.skip/
* @api public
*/
/**
* Specifies the maxScan option.
*
* ####Example
*
* query.maxScan(100)
*
* ####Note
*
* Cannot be used with `distinct()`
*
* @method maxScan
* @memberOf Query
* @instance
* @param {Number} val
* @see maxScan http://docs.mongodb.org/manual/reference/operator/maxScan/
* @api public
*/
/**
* Specifies the batchSize option.
*
* ####Example
*
* query.batchSize(100)
*
* ####Note
*
* Cannot be used with `distinct()`
*
* @method batchSize
* @memberOf Query
* @instance
* @param {Number} val
* @see batchSize http://docs.mongodb.org/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 http://docs.mongodb.org/manual/reference/operator/comment/
* @api public
*/
/**
* Specifies this query as a `snapshot` query.
*
* ####Example
*
* query.snapshot() // true
* query.snapshot(true)
* query.snapshot(false)
*
* ####Note
*
* Cannot be used with `distinct()`
*
* @method snapshot
* @memberOf Query
* @instance
* @see snapshot http://docs.mongodb.org/manual/reference/operator/snapshot/
* @return {Query} this
* @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 http://docs.mongodb.org/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")
*
* When using string syntax, prefixing a path with `-` will flag that path as excluded. When a path does not have the `-` prefix, it is included. Lastly, if a path is prefixed with `+`, it forces inclusion of the path, which is useful for paths excluded at the [schema level](/docs/api.html#schematype_SchemaType-select).
*
* A projection _must_ be either inclusive or exclusive. In other words, you must
* either list the fields to include (which excludes all others), or list the fields
* to exclude (which implies all other fields are included). The [`_id` field is the only exception because MongoDB includes it by default](https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/#suppress-id-field).
*
* ####Example
*
* // include a and b, exclude other fields
* query.select('a b');
*
* // exclude c and d, include other fields
* query.select('-c -d');
*
* // Use `+` to override schema-level `select: false` without making the
* // projection inclusive.
* const schema = new Schema({
* foo: { type: String, select: false },
* bar: String
* });
* // ...
* query.select('+foo'); // Override foo's `select: false` without excluding `bar`
*
* // or you may use object notation, useful when
* // you have keys already prefixed with a "-"
* query.select({ a: 1, b: 1 });
* query.select({ c: 0, d: 0 });
*
*
* @method select
* @memberOf Query
* @instance
* @param {Object|String} arg
* @return {Query} this
* @see SchemaType
* @api public
*/
Query.prototype.select = function select() {
let arg = arguments[0];
if (!arg) return this;
let i;
let len;
if (arguments.length !== 1) {
throw new Error('Invalid select: select only takes 1 argument');
}
this._validate('select');
const fields = this._fields || (this._fields = {});
const userProvidedFields = this._userProvidedFields || (this._userProvidedFields = {});
const type = typeof arg;
if (('string' == type || Object.prototype.toString.call(arg) === '[object Arguments]') &&
'number' == typeof arg.length || Array.isArray(arg)) {
if ('string' == type)
arg = arg.split(/\s+/);
for (i = 0, len = arg.length; i < len; ++i) {
let field = arg[i];
if (!field) continue;
const include = '-' == field[0] ? 0 : 1;
if (include === 0) field = field.substring(1);
fields[field] = include;
userProvidedFields[field] = include;
}
return this;
}
if (utils.isObject(arg)) {
const keys = Object.keys(arg);
for (i = 0; i < keys.length; ++i) {
fields[keys[i]] = arg[keys[i]];
userProvidedFields[keys[i]] = arg[keys[i]];
}
return this;
}
throw new TypeError('Invalid select() argument. Must be string or object.');
};
/**
* _DEPRECATED_ Sets the slaveOk option.
*
* **Deprecated** in MongoDB 2.2 in favor of [read preferences](#query_Query-read).
*
* ####Example:
*
* query.slaveOk() // true
* query.slaveOk(true)
* query.slaveOk(false)
*
* @method slaveOk
* @memberOf Query
* @instance
* @deprecated use read() preferences instead if on mongodb >= 2.2
* @param {Boolean} v defaults to true
* @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference
* @see slaveOk http://docs.mongodb.org/manual/reference/method/rs.slaveOk/
* @see read() #query_Query-read
* @return {Query} this
* @api public
*/
/**
* Determines the MongoDB nodes from which to read.
*
* ####Preferences: