UNPKG

142 kBJavaScriptView Raw
1'use strict';
2
3/*!
4 * Module dependencies.
5 */
6
7const CastError = require('./error/cast');
8const DocumentNotFoundError = require('./error/notFound');
9const Kareem = require('kareem');
10const ObjectParameterError = require('./error/objectParameter');
11const QueryCursor = require('./cursor/QueryCursor');
12const ReadPreference = require('./driver').get().ReadPreference;
13const applyWriteConcern = require('./helpers/schema/applyWriteConcern');
14const cast = require('./cast');
15const castArrayFilters = require('./helpers/update/castArrayFilters');
16const castUpdate = require('./helpers/query/castUpdate');
17const completeMany = require('./helpers/query/completeMany');
18const get = require('./helpers/get');
19const hasDollarKeys = require('./helpers/query/hasDollarKeys');
20const helpers = require('./queryhelpers');
21const isInclusive = require('./helpers/projection/isInclusive');
22const mquery = require('mquery');
23const selectPopulatedFields = require('./helpers/query/selectPopulatedFields');
24const setDefaultsOnInsert = require('./helpers/setDefaultsOnInsert');
25const slice = require('sliced');
26const updateValidators = require('./helpers/updateValidators');
27const util = require('util');
28const utils = require('./utils');
29const wrapThunk = require('./helpers/query/wrapThunk');
30
31/**
32 * Query constructor used for building queries. You do not need
33 * to instantiate a `Query` directly. Instead use Model functions like
34 * [`Model.find()`](/docs/api.html#find_find).
35 *
36 * ####Example:
37 *
38 * const query = MyModel.find(); // `query` is an instance of `Query`
39 * query.setOptions({ lean : true });
40 * query.collection(MyModel.collection);
41 * query.where('age').gte(21).exec(callback);
42 *
43 * // You can instantiate a query directly. There is no need to do
44 * // this unless you're an advanced user with a very good reason to.
45 * const query = new mongoose.Query();
46 *
47 * @param {Object} [options]
48 * @param {Object} [model]
49 * @param {Object} [conditions]
50 * @param {Object} [collection] Mongoose collection
51 * @api public
52 */
53
54function Query(conditions, options, model, collection) {
55 // this stuff is for dealing with custom queries created by #toConstructor
56 if (!this._mongooseOptions) {
57 this._mongooseOptions = {};
58 }
59 options = options || {};
60
61 this._transforms = [];
62 this._hooks = new Kareem();
63 this._executionCount = 0;
64
65 // this is the case where we have a CustomQuery, we need to check if we got
66 // options passed in, and if we did, merge them in
67 const keys = Object.keys(options);
68 for (let i = 0; i < keys.length; ++i) {
69 const k = keys[i];
70 this._mongooseOptions[k] = options[k];
71 }
72
73 if (collection) {
74 this.mongooseCollection = collection;
75 }
76
77 if (model) {
78 this.model = model;
79 this.schema = model.schema;
80 }
81
82 // this is needed because map reduce returns a model that can be queried, but
83 // all of the queries on said model should be lean
84 if (this.model && this.model._mapreduce) {
85 this.lean();
86 }
87
88 // inherit mquery
89 mquery.call(this, this.mongooseCollection, options);
90
91 if (conditions) {
92 this.find(conditions);
93 }
94
95 this.options = this.options || {};
96
97 // For gh-6880. mquery still needs to support `fields` by default for old
98 // versions of MongoDB
99 this.$useProjection = true;
100
101 const collation = get(this, 'schema.options.collation', null);
102 if (collation != null) {
103 this.options.collation = collation;
104 }
105}
106
107/*!
108 * inherit mquery
109 */
110
111Query.prototype = new mquery;
112Query.prototype.constructor = Query;
113Query.base = mquery.prototype;
114
115/**
116 * Flag to opt out of using `$geoWithin`.
117 *
118 * mongoose.Query.use$geoWithin = false;
119 *
120 * 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.
121 *
122 * @see http://docs.mongodb.org/manual/reference/operator/geoWithin/
123 * @default true
124 * @property use$geoWithin
125 * @memberOf Query
126 * @receiver Query
127 * @api public
128 */
129
130Query.use$geoWithin = mquery.use$geoWithin;
131
132/**
133 * Converts this query to a customized, reusable query constructor with all arguments and options retained.
134 *
135 * ####Example
136 *
137 * // Create a query for adventure movies and read from the primary
138 * // node in the replica-set unless it is down, in which case we'll
139 * // read from a secondary node.
140 * var query = Movie.find({ tags: 'adventure' }).read('primaryPreferred');
141 *
142 * // create a custom Query constructor based off these settings
143 * var Adventure = query.toConstructor();
144 *
145 * // Adventure is now a subclass of mongoose.Query and works the same way but with the
146 * // default query parameters and options set.
147 * Adventure().exec(callback)
148 *
149 * // further narrow down our query results while still using the previous settings
150 * Adventure().where({ name: /^Life/ }).exec(callback);
151 *
152 * // since Adventure is a stand-alone constructor we can also add our own
153 * // helper methods and getters without impacting global queries
154 * Adventure.prototype.startsWith = function (prefix) {
155 * this.where({ name: new RegExp('^' + prefix) })
156 * return this;
157 * }
158 * Object.defineProperty(Adventure.prototype, 'highlyRated', {
159 * get: function () {
160 * this.where({ rating: { $gt: 4.5 }});
161 * return this;
162 * }
163 * })
164 * Adventure().highlyRated.startsWith('Life').exec(callback)
165 *
166 * New in 3.7.3
167 *
168 * @return {Query} subclass-of-Query
169 * @api public
170 */
171
172Query.prototype.toConstructor = function toConstructor() {
173 const model = this.model;
174 const coll = this.mongooseCollection;
175
176 const CustomQuery = function(criteria, options) {
177 if (!(this instanceof CustomQuery)) {
178 return new CustomQuery(criteria, options);
179 }
180 this._mongooseOptions = utils.clone(p._mongooseOptions);
181 Query.call(this, criteria, options || null, model, coll);
182 };
183
184 util.inherits(CustomQuery, model.Query);
185
186 // set inherited defaults
187 const p = CustomQuery.prototype;
188
189 p.options = {};
190
191 p.setOptions(this.options);
192
193 p.op = this.op;
194 p._conditions = utils.clone(this._conditions);
195 p._fields = utils.clone(this._fields);
196 p._update = utils.clone(this._update, {
197 flattenDecimals: false
198 });
199 p._path = this._path;
200 p._distinct = this._distinct;
201 p._collection = this._collection;
202 p._mongooseOptions = this._mongooseOptions;
203
204 return CustomQuery;
205};
206
207/**
208 * Specifies a javascript function or expression to pass to MongoDBs query system.
209 *
210 * ####Example
211 *
212 * query.$where('this.comments.length === 10 || this.name.length === 5')
213 *
214 * // or
215 *
216 * query.$where(function () {
217 * return this.comments.length === 10 || this.name.length === 5;
218 * })
219 *
220 * ####NOTE:
221 *
222 * Only use `$where` when you have a condition that cannot be met using other MongoDB operators like `$lt`.
223 * **Be sure to read about all of [its caveats](http://docs.mongodb.org/manual/reference/operator/where/) before using.**
224 *
225 * @see $where http://docs.mongodb.org/manual/reference/operator/where/
226 * @method $where
227 * @param {String|Function} js javascript string or function
228 * @return {Query} this
229 * @memberOf Query
230 * @instance
231 * @method $where
232 * @api public
233 */
234
235/**
236 * Specifies a `path` for use with chaining.
237 *
238 * ####Example
239 *
240 * // instead of writing:
241 * User.find({age: {$gte: 21, $lte: 65}}, callback);
242 *
243 * // we can instead write:
244 * User.where('age').gte(21).lte(65);
245 *
246 * // passing query conditions is permitted
247 * User.find().where({ name: 'vonderful' })
248 *
249 * // chaining
250 * User
251 * .where('age').gte(21).lte(65)
252 * .where('name', /^vonderful/i)
253 * .where('friends').slice(10)
254 * .exec(callback)
255 *
256 * @method where
257 * @memberOf Query
258 * @instance
259 * @param {String|Object} [path]
260 * @param {any} [val]
261 * @return {Query} this
262 * @api public
263 */
264
265Query.prototype.slice = function() {
266 if (arguments.length === 0) {
267 return this;
268 }
269
270 this._validate('slice');
271
272 let path;
273 let val;
274
275 if (arguments.length === 1) {
276 const arg = arguments[0];
277 if (typeof arg === 'object' && !Array.isArray(arg)) {
278 const keys = Object.keys(arg);
279 const numKeys = keys.length;
280 for (let i = 0; i < numKeys; ++i) {
281 this.slice(keys[i], arg[keys[i]]);
282 }
283 return this;
284 }
285 this._ensurePath('slice');
286 path = this._path;
287 val = arguments[0];
288 } else if (arguments.length === 2) {
289 if ('number' === typeof arguments[0]) {
290 this._ensurePath('slice');
291 path = this._path;
292 val = slice(arguments);
293 } else {
294 path = arguments[0];
295 val = arguments[1];
296 }
297 } else if (arguments.length === 3) {
298 path = arguments[0];
299 val = slice(arguments, 1);
300 }
301
302 const p = {};
303 p[path] = { $slice: val };
304 this.select(p);
305
306 return this;
307};
308
309
310/**
311 * Specifies the complementary comparison value for paths specified with `where()`
312 *
313 * ####Example
314 *
315 * User.where('age').equals(49);
316 *
317 * // is the same as
318 *
319 * User.where('age', 49);
320 *
321 * @method equals
322 * @memberOf Query
323 * @instance
324 * @param {Object} val
325 * @return {Query} this
326 * @api public
327 */
328
329/**
330 * Specifies arguments for an `$or` condition.
331 *
332 * ####Example
333 *
334 * query.or([{ color: 'red' }, { status: 'emergency' }])
335 *
336 * @see $or http://docs.mongodb.org/manual/reference/operator/or/
337 * @method or
338 * @memberOf Query
339 * @instance
340 * @param {Array} array array of conditions
341 * @return {Query} this
342 * @api public
343 */
344
345/**
346 * Specifies arguments for a `$nor` condition.
347 *
348 * ####Example
349 *
350 * query.nor([{ color: 'green' }, { status: 'ok' }])
351 *
352 * @see $nor http://docs.mongodb.org/manual/reference/operator/nor/
353 * @method nor
354 * @memberOf Query
355 * @instance
356 * @param {Array} array array of conditions
357 * @return {Query} this
358 * @api public
359 */
360
361/**
362 * Specifies arguments for a `$and` condition.
363 *
364 * ####Example
365 *
366 * query.and([{ color: 'green' }, { status: 'ok' }])
367 *
368 * @method and
369 * @memberOf Query
370 * @instance
371 * @see $and http://docs.mongodb.org/manual/reference/operator/and/
372 * @param {Array} array array of conditions
373 * @return {Query} this
374 * @api public
375 */
376
377/**
378 * Specifies a $gt query condition.
379 *
380 * When called with one argument, the most recent path passed to `where()` is used.
381 *
382 * ####Example
383 *
384 * Thing.find().where('age').gt(21)
385 *
386 * // or
387 * Thing.find().gt('age', 21)
388 *
389 * @method gt
390 * @memberOf Query
391 * @instance
392 * @param {String} [path]
393 * @param {Number} val
394 * @see $gt http://docs.mongodb.org/manual/reference/operator/gt/
395 * @api public
396 */
397
398/**
399 * Specifies a $gte query condition.
400 *
401 * When called with one argument, the most recent path passed to `where()` is used.
402 *
403 * @method gte
404 * @memberOf Query
405 * @instance
406 * @param {String} [path]
407 * @param {Number} val
408 * @see $gte http://docs.mongodb.org/manual/reference/operator/gte/
409 * @api public
410 */
411
412/**
413 * Specifies a $lt query condition.
414 *
415 * When called with one argument, the most recent path passed to `where()` is used.
416 *
417 * @method lt
418 * @memberOf Query
419 * @instance
420 * @param {String} [path]
421 * @param {Number} val
422 * @see $lt http://docs.mongodb.org/manual/reference/operator/lt/
423 * @api public
424 */
425
426/**
427 * Specifies a $lte query condition.
428 *
429 * When called with one argument, the most recent path passed to `where()` is used.
430 *
431 * @method lte
432 * @see $lte http://docs.mongodb.org/manual/reference/operator/lte/
433 * @memberOf Query
434 * @instance
435 * @param {String} [path]
436 * @param {Number} val
437 * @api public
438 */
439
440/**
441 * Specifies a $ne query condition.
442 *
443 * When called with one argument, the most recent path passed to `where()` is used.
444 *
445 * @see $ne http://docs.mongodb.org/manual/reference/operator/ne/
446 * @method ne
447 * @memberOf Query
448 * @instance
449 * @param {String} [path]
450 * @param {Number} val
451 * @api public
452 */
453
454/**
455 * Specifies an $in query condition.
456 *
457 * When called with one argument, the most recent path passed to `where()` is used.
458 *
459 * @see $in http://docs.mongodb.org/manual/reference/operator/in/
460 * @method in
461 * @memberOf Query
462 * @instance
463 * @param {String} [path]
464 * @param {Number} val
465 * @api public
466 */
467
468/**
469 * Specifies an $nin query condition.
470 *
471 * When called with one argument, the most recent path passed to `where()` is used.
472 *
473 * @see $nin http://docs.mongodb.org/manual/reference/operator/nin/
474 * @method nin
475 * @memberOf Query
476 * @instance
477 * @param {String} [path]
478 * @param {Number} val
479 * @api public
480 */
481
482/**
483 * Specifies an $all query condition.
484 *
485 * When called with one argument, the most recent path passed to `where()` is used.
486 *
487 * @see $all http://docs.mongodb.org/manual/reference/operator/all/
488 * @method all
489 * @memberOf Query
490 * @instance
491 * @param {String} [path]
492 * @param {Number} val
493 * @api public
494 */
495
496/**
497 * Specifies a $size query condition.
498 *
499 * When called with one argument, the most recent path passed to `where()` is used.
500 *
501 * ####Example
502 *
503 * MyModel.where('tags').size(0).exec(function (err, docs) {
504 * if (err) return handleError(err);
505 *
506 * assert(Array.isArray(docs));
507 * console.log('documents with 0 tags', docs);
508 * })
509 *
510 * @see $size http://docs.mongodb.org/manual/reference/operator/size/
511 * @method size
512 * @memberOf Query
513 * @instance
514 * @param {String} [path]
515 * @param {Number} val
516 * @api public
517 */
518
519/**
520 * Specifies a $regex query condition.
521 *
522 * When called with one argument, the most recent path passed to `where()` is used.
523 *
524 * @see $regex http://docs.mongodb.org/manual/reference/operator/regex/
525 * @method regex
526 * @memberOf Query
527 * @instance
528 * @param {String} [path]
529 * @param {String|RegExp} val
530 * @api public
531 */
532
533/**
534 * Specifies a $maxDistance query condition.
535 *
536 * When called with one argument, the most recent path passed to `where()` is used.
537 *
538 * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/
539 * @method maxDistance
540 * @memberOf Query
541 * @instance
542 * @param {String} [path]
543 * @param {Number} val
544 * @api public
545 */
546
547/**
548 * Specifies a `$mod` condition, filters documents for documents whose
549 * `path` property is a number that is equal to `remainder` modulo `divisor`.
550 *
551 * ####Example
552 *
553 * // All find products whose inventory is odd
554 * Product.find().mod('inventory', [2, 1]);
555 * Product.find().where('inventory').mod([2, 1]);
556 * // This syntax is a little strange, but supported.
557 * Product.find().where('inventory').mod(2, 1);
558 *
559 * @method mod
560 * @memberOf Query
561 * @instance
562 * @param {String} [path]
563 * @param {Array} val must be of length 2, first element is `divisor`, 2nd element is `remainder`.
564 * @return {Query} this
565 * @see $mod http://docs.mongodb.org/manual/reference/operator/mod/
566 * @api public
567 */
568
569Query.prototype.mod = function() {
570 let val;
571 let path;
572
573 if (arguments.length === 1) {
574 this._ensurePath('mod');
575 val = arguments[0];
576 path = this._path;
577 } else if (arguments.length === 2 && !Array.isArray(arguments[1])) {
578 this._ensurePath('mod');
579 val = slice(arguments);
580 path = this._path;
581 } else if (arguments.length === 3) {
582 val = slice(arguments, 1);
583 path = arguments[0];
584 } else {
585 val = arguments[1];
586 path = arguments[0];
587 }
588
589 const conds = this._conditions[path] || (this._conditions[path] = {});
590 conds.$mod = val;
591 return this;
592};
593
594/**
595 * Specifies an `$exists` condition
596 *
597 * ####Example
598 *
599 * // { name: { $exists: true }}
600 * Thing.where('name').exists()
601 * Thing.where('name').exists(true)
602 * Thing.find().exists('name')
603 *
604 * // { name: { $exists: false }}
605 * Thing.where('name').exists(false);
606 * Thing.find().exists('name', false);
607 *
608 * @method exists
609 * @memberOf Query
610 * @instance
611 * @param {String} [path]
612 * @param {Number} val
613 * @return {Query} this
614 * @see $exists http://docs.mongodb.org/manual/reference/operator/exists/
615 * @api public
616 */
617
618/**
619 * Specifies an `$elemMatch` condition
620 *
621 * ####Example
622 *
623 * query.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}})
624 *
625 * query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}})
626 *
627 * query.elemMatch('comment', function (elem) {
628 * elem.where('author').equals('autobot');
629 * elem.where('votes').gte(5);
630 * })
631 *
632 * query.where('comment').elemMatch(function (elem) {
633 * elem.where({ author: 'autobot' });
634 * elem.where('votes').gte(5);
635 * })
636 *
637 * @method elemMatch
638 * @memberOf Query
639 * @instance
640 * @param {String|Object|Function} path
641 * @param {Object|Function} criteria
642 * @return {Query} this
643 * @see $elemMatch http://docs.mongodb.org/manual/reference/operator/elemMatch/
644 * @api public
645 */
646
647/**
648 * Defines a `$within` or `$geoWithin` argument for geo-spatial queries.
649 *
650 * ####Example
651 *
652 * query.where(path).within().box()
653 * query.where(path).within().circle()
654 * query.where(path).within().geometry()
655 *
656 * query.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true });
657 * query.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] });
658 * query.where('loc').within({ polygon: [[],[],[],[]] });
659 *
660 * query.where('loc').within([], [], []) // polygon
661 * query.where('loc').within([], []) // box
662 * query.where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry
663 *
664 * **MUST** be used after `where()`.
665 *
666 * ####NOTE:
667 *
668 * As of Mongoose 3.7, `$geoWithin` is always used for queries. To change this behavior, see [Query.use$geoWithin](#query_Query-use%2524geoWithin).
669 *
670 * ####NOTE:
671 *
672 * 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).
673 *
674 * @method within
675 * @see $polygon http://docs.mongodb.org/manual/reference/operator/polygon/
676 * @see $box http://docs.mongodb.org/manual/reference/operator/box/
677 * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/
678 * @see $center http://docs.mongodb.org/manual/reference/operator/center/
679 * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/
680 * @memberOf Query
681 * @instance
682 * @return {Query} this
683 * @api public
684 */
685
686/**
687 * Specifies a $slice projection for an array.
688 *
689 * ####Example
690 *
691 * query.slice('comments', 5)
692 * query.slice('comments', -5)
693 * query.slice('comments', [10, 5])
694 * query.where('comments').slice(5)
695 * query.where('comments').slice([-10, 5])
696 *
697 * @method slice
698 * @memberOf Query
699 * @instance
700 * @param {String} [path]
701 * @param {Number} val number/range of elements to slice
702 * @return {Query} this
703 * @see mongodb http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields#RetrievingaSubsetofFields-RetrievingaSubrangeofArrayElements
704 * @see $slice http://docs.mongodb.org/manual/reference/projection/slice/#prj._S_slice
705 * @api public
706 */
707
708/**
709 * Specifies the maximum number of documents the query will return.
710 *
711 * ####Example
712 *
713 * query.limit(20)
714 *
715 * ####Note
716 *
717 * Cannot be used with `distinct()`
718 *
719 * @method limit
720 * @memberOf Query
721 * @instance
722 * @param {Number} val
723 * @api public
724 */
725
726/**
727 * Specifies the number of documents to skip.
728 *
729 * ####Example
730 *
731 * query.skip(100).limit(20)
732 *
733 * ####Note
734 *
735 * Cannot be used with `distinct()`
736 *
737 * @method skip
738 * @memberOf Query
739 * @instance
740 * @param {Number} val
741 * @see cursor.skip http://docs.mongodb.org/manual/reference/method/cursor.skip/
742 * @api public
743 */
744
745/**
746 * Specifies the maxScan option.
747 *
748 * ####Example
749 *
750 * query.maxScan(100)
751 *
752 * ####Note
753 *
754 * Cannot be used with `distinct()`
755 *
756 * @method maxScan
757 * @memberOf Query
758 * @instance
759 * @param {Number} val
760 * @see maxScan http://docs.mongodb.org/manual/reference/operator/maxScan/
761 * @api public
762 */
763
764/**
765 * Specifies the batchSize option.
766 *
767 * ####Example
768 *
769 * query.batchSize(100)
770 *
771 * ####Note
772 *
773 * Cannot be used with `distinct()`
774 *
775 * @method batchSize
776 * @memberOf Query
777 * @instance
778 * @param {Number} val
779 * @see batchSize http://docs.mongodb.org/manual/reference/method/cursor.batchSize/
780 * @api public
781 */
782
783/**
784 * Specifies the `comment` option.
785 *
786 * ####Example
787 *
788 * query.comment('login query')
789 *
790 * ####Note
791 *
792 * Cannot be used with `distinct()`
793 *
794 * @method comment
795 * @memberOf Query
796 * @instance
797 * @param {Number} val
798 * @see comment http://docs.mongodb.org/manual/reference/operator/comment/
799 * @api public
800 */
801
802/**
803 * Specifies this query as a `snapshot` query.
804 *
805 * ####Example
806 *
807 * query.snapshot() // true
808 * query.snapshot(true)
809 * query.snapshot(false)
810 *
811 * ####Note
812 *
813 * Cannot be used with `distinct()`
814 *
815 * @method snapshot
816 * @memberOf Query
817 * @instance
818 * @see snapshot http://docs.mongodb.org/manual/reference/operator/snapshot/
819 * @return {Query} this
820 * @api public
821 */
822
823/**
824 * Sets query hints.
825 *
826 * ####Example
827 *
828 * query.hint({ indexA: 1, indexB: -1})
829 *
830 * ####Note
831 *
832 * Cannot be used with `distinct()`
833 *
834 * @method hint
835 * @memberOf Query
836 * @instance
837 * @param {Object} val a hint object
838 * @return {Query} this
839 * @see $hint http://docs.mongodb.org/manual/reference/operator/hint/
840 * @api public
841 */
842
843/**
844 * Specifies which document fields to include or exclude (also known as the query "projection")
845 *
846 * 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).
847 *
848 * A projection _must_ be either inclusive or exclusive. In other words, you must
849 * either list the fields to include (which excludes all others), or list the fields
850 * 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).
851 *
852 * ####Example
853 *
854 * // include a and b, exclude other fields
855 * query.select('a b');
856 *
857 * // exclude c and d, include other fields
858 * query.select('-c -d');
859 *
860 * // Use `+` to override schema-level `select: false` without making the
861 * // projection inclusive.
862 * const schema = new Schema({
863 * foo: { type: String, select: false },
864 * bar: String
865 * });
866 * // ...
867 * query.select('+foo'); // Override foo's `select: false` without excluding `bar`
868 *
869 * // or you may use object notation, useful when
870 * // you have keys already prefixed with a "-"
871 * query.select({ a: 1, b: 1 });
872 * query.select({ c: 0, d: 0 });
873 *
874 *
875 * @method select
876 * @memberOf Query
877 * @instance
878 * @param {Object|String} arg
879 * @return {Query} this
880 * @see SchemaType
881 * @api public
882 */
883
884Query.prototype.select = function select() {
885 let arg = arguments[0];
886 if (!arg) return this;
887 let i;
888 let len;
889
890 if (arguments.length !== 1) {
891 throw new Error('Invalid select: select only takes 1 argument');
892 }
893
894 this._validate('select');
895
896 const fields = this._fields || (this._fields = {});
897 const userProvidedFields = this._userProvidedFields || (this._userProvidedFields = {});
898 const type = typeof arg;
899
900 if (('string' == type || Object.prototype.toString.call(arg) === '[object Arguments]') &&
901 'number' == typeof arg.length || Array.isArray(arg)) {
902 if ('string' == type)
903 arg = arg.split(/\s+/);
904
905 for (i = 0, len = arg.length; i < len; ++i) {
906 let field = arg[i];
907 if (!field) continue;
908 const include = '-' == field[0] ? 0 : 1;
909 if (include === 0) field = field.substring(1);
910 fields[field] = include;
911 userProvidedFields[field] = include;
912 }
913 return this;
914 }
915
916 if (utils.isObject(arg)) {
917 const keys = Object.keys(arg);
918 for (i = 0; i < keys.length; ++i) {
919 fields[keys[i]] = arg[keys[i]];
920 userProvidedFields[keys[i]] = arg[keys[i]];
921 }
922 return this;
923 }
924
925 throw new TypeError('Invalid select() argument. Must be string or object.');
926};
927
928/**
929 * _DEPRECATED_ Sets the slaveOk option.
930 *
931 * **Deprecated** in MongoDB 2.2 in favor of [read preferences](#query_Query-read).
932 *
933 * ####Example:
934 *
935 * query.slaveOk() // true
936 * query.slaveOk(true)
937 * query.slaveOk(false)
938 *
939 * @method slaveOk
940 * @memberOf Query
941 * @instance
942 * @deprecated use read() preferences instead if on mongodb >= 2.2
943 * @param {Boolean} v defaults to true
944 * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference
945 * @see slaveOk http://docs.mongodb.org/manual/reference/method/rs.slaveOk/
946 * @see read() #query_Query-read
947 * @return {Query} this
948 * @api public
949 */
950
951/**
952 * Determines the MongoDB nodes from which to read.
953 *
954 * ####Preferences:
955 *
956 * primary - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags.
957 * secondary Read from secondary if available, otherwise error.
958 * primaryPreferred Read from primary if available, otherwise a secondary.
959 * secondaryPreferred Read from a secondary if available, otherwise read from the primary.
960 * nearest All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the random selection.
961 *
962 * Aliases
963 *
964 * p primary
965 * pp primaryPreferred
966 * s secondary
967 * sp secondaryPreferred
968 * n nearest
969 *
970 * ####Example:
971 *
972 * new Query().read('primary')
973 * new Query().read('p') // same as primary
974 *
975 * new Query().read('primaryPreferred')
976 * new Query().read('pp') // same as primaryPreferred
977 *
978 * new Query().read('secondary')
979 * new Query().read('s') // same as secondary
980 *
981 * new Query().read('secondaryPreferred')
982 * new Query().read('sp') // same as secondaryPreferred
983 *
984 * new Query().read('nearest')
985 * new Query().read('n') // same as nearest
986 *
987 * // read from secondaries with matching tags
988 * new Query().read('s', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }])
989 *
990 * Read more about how to use read preferrences [here](http://docs.mongodb.org/manual/applications/replication/#read-preference) and [here](http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences).
991 *
992 * @method read
993 * @memberOf Query
994 * @instance
995 * @param {String} pref one of the listed preference options or aliases
996 * @param {Array} [tags] optional tags for this query
997 * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference
998 * @see driver http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences
999 * @return {Query} this
1000 * @api public
1001 */
1002
1003Query.prototype.read = function read(pref, tags) {
1004 // first cast into a ReadPreference object to support tags
1005 const read = new ReadPreference(pref, tags);
1006 this.options.readPreference = read;
1007 return this;
1008};
1009
1010/**
1011 * Sets the [MongoDB session](https://docs.mongodb.com/manual/reference/server-sessions/)
1012 * associated with this query. Sessions are how you mark a query as part of a
1013 * [transaction](/docs/transactions.html).
1014 *
1015 * Calling `session(null)` removes the session from this query.
1016 *
1017 * ####Example:
1018 *
1019 * const s = await mongoose.startSession();
1020 * await mongoose.model('Person').findOne({ name: 'Axl Rose' }).session(s);
1021 *
1022 * @method session
1023 * @memberOf Query
1024 * @instance
1025 * @param {ClientSession} [session] from `await conn.startSession()`
1026 * @see Connection.prototype.startSession() /docs/api.html#connection_Connection-startSession
1027 * @see mongoose.startSession() /docs/api.html#mongoose_Mongoose-startSession
1028 * @return {Query} this
1029 * @api public
1030 */
1031
1032Query.prototype.session = function session(v) {
1033 if (v == null) {
1034 delete this.options.session;
1035 }
1036 this.options.session = v;
1037 return this;
1038};
1039
1040/**
1041 * Sets the specified number of `mongod` servers, or tag set of `mongod` servers,
1042 * that must acknowledge this write before this write is considered successful.
1043 * This option is only valid for operations that write to the database:
1044 *
1045 * - `deleteOne()`
1046 * - `deleteMany()`
1047 * - `findOneAndDelete()`
1048 * - `findOneAndReplace()`
1049 * - `findOneAndUpdate()`
1050 * - `remove()`
1051 * - `update()`
1052 * - `updateOne()`
1053 * - `updateMany()`
1054 *
1055 * Defaults to the schema's [`writeConcern.w` option](/docs/guide.html#writeConcern)
1056 *
1057 * ####Example:
1058 *
1059 * // The 'majority' option means the `deleteOne()` promise won't resolve
1060 * // until the `deleteOne()` has propagated to the majority of the replica set
1061 * await mongoose.model('Person').
1062 * deleteOne({ name: 'Ned Stark' }).
1063 * w('majority');
1064 *
1065 * @method w
1066 * @memberOf Query
1067 * @instance
1068 * @param {String|number} val 0 for fire-and-forget, 1 for acknowledged by one server, 'majority' for majority of the replica set, or [any of the more advanced options](https://docs.mongodb.com/manual/reference/write-concern/#w-option).
1069 * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#w-option
1070 * @return {Query} this
1071 * @api public
1072 */
1073
1074Query.prototype.w = function w(val) {
1075 if (val == null) {
1076 delete this.options.w;
1077 }
1078 this.options.w = val;
1079 return this;
1080};
1081
1082/**
1083 * Requests acknowledgement that this operation has been persisted to MongoDB's
1084 * on-disk journal.
1085 * This option is only valid for operations that write to the database:
1086 *
1087 * - `deleteOne()`
1088 * - `deleteMany()`
1089 * - `findOneAndDelete()`
1090 * - `findOneAndReplace()`
1091 * - `findOneAndUpdate()`
1092 * - `remove()`
1093 * - `update()`
1094 * - `updateOne()`
1095 * - `updateMany()`
1096 *
1097 * Defaults to the schema's [`writeConcern.j` option](/docs/guide.html#writeConcern)
1098 *
1099 * ####Example:
1100 *
1101 * await mongoose.model('Person').deleteOne({ name: 'Ned Stark' }).j(true);
1102 *
1103 * @method j
1104 * @memberOf Query
1105 * @instance
1106 * @param {boolean} val
1107 * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#j-option
1108 * @return {Query} this
1109 * @api public
1110 */
1111
1112Query.prototype.j = function j(val) {
1113 if (val == null) {
1114 delete this.options.j;
1115 }
1116 this.options.j = val;
1117 return this;
1118};
1119
1120/**
1121 * If [`w > 1`](/docs/api.html#query_Query-w), the maximum amount of time to
1122 * wait for this write to propagate through the replica set before this
1123 * operation fails. The default is `0`, which means no timeout.
1124 *
1125 * This option is only valid for operations that write to the database:
1126 *
1127 * - `deleteOne()`
1128 * - `deleteMany()`
1129 * - `findOneAndDelete()`
1130 * - `findOneAndReplace()`
1131 * - `findOneAndUpdate()`
1132 * - `remove()`
1133 * - `update()`
1134 * - `updateOne()`
1135 * - `updateMany()`
1136 *
1137 * Defaults to the schema's [`writeConcern.wtimeout` option](/docs/guide.html#writeConcern)
1138 *
1139 * ####Example:
1140 *
1141 * // The `deleteOne()` promise won't resolve until this `deleteOne()` has
1142 * // propagated to at least `w = 2` members of the replica set. If it takes
1143 * // longer than 1 second, this `deleteOne()` will fail.
1144 * await mongoose.model('Person').
1145 * deleteOne({ name: 'Ned Stark' }).
1146 * w(2).
1147 * wtimeout(1000);
1148 *
1149 * @method wtimeout
1150 * @memberOf Query
1151 * @instance
1152 * @param {number} ms number of milliseconds to wait
1153 * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#wtimeout
1154 * @return {Query} this
1155 * @api public
1156 */
1157
1158Query.prototype.wtimeout = function wtimeout(ms) {
1159 if (ms == null) {
1160 delete this.options.wtimeout;
1161 }
1162 this.options.wtimeout = ms;
1163 return this;
1164};
1165
1166/**
1167 * Sets the readConcern option for the query.
1168 *
1169 * ####Example:
1170 *
1171 * new Query().readConcern('local')
1172 * new Query().readConcern('l') // same as local
1173 *
1174 * new Query().readConcern('available')
1175 * new Query().readConcern('a') // same as available
1176 *
1177 * new Query().readConcern('majority')
1178 * new Query().readConcern('m') // same as majority
1179 *
1180 * new Query().readConcern('linearizable')
1181 * new Query().readConcern('lz') // same as linearizable
1182 *
1183 * new Query().readConcern('snapshot')
1184 * new Query().readConcern('s') // same as snapshot
1185 *
1186 *
1187 * ####Read Concern Level:
1188 *
1189 * local MongoDB 3.2+ The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back).
1190 * available MongoDB 3.6+ The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back).
1191 * majority MongoDB 3.2+ The query returns the data that has been acknowledged by a majority of the replica set members. The documents returned by the read operation are durable, even in the event of failure.
1192 * linearizable MongoDB 3.4+ The query returns data that reflects all successful majority-acknowledged writes that completed prior to the start of the read operation. The query may wait for concurrently executing writes to propagate to a majority of replica set members before returning results.
1193 * snapshot MongoDB 4.0+ Only available for operations within multi-document transactions. Upon transaction commit with write concern "majority", the transaction operations are guaranteed to have read from a snapshot of majority-committed data.
1194 *
1195 * Aliases
1196 *
1197 * l local
1198 * a available
1199 * m majority
1200 * lz linearizable
1201 * s snapshot
1202 *
1203 * Read more about how to use read concern [here](https://docs.mongodb.com/manual/reference/read-concern/).
1204 *
1205 * @memberOf Query
1206 * @method readConcern
1207 * @param {String} level one of the listed read concern level or their aliases
1208 * @see mongodb https://docs.mongodb.com/manual/reference/read-concern/
1209 * @return {Query} this
1210 * @api public
1211 */
1212
1213/**
1214 * Merges another Query or conditions object into this one.
1215 *
1216 * When a Query is passed, conditions, field selection and options are merged.
1217 *
1218 * New in 3.7.0
1219 *
1220 * @method merge
1221 * @memberOf Query
1222 * @instance
1223 * @param {Query|Object} source
1224 * @return {Query} this
1225 */
1226
1227/**
1228 * Gets query options.
1229 *
1230 * ####Example:
1231 *
1232 * var query = new Query();
1233 * query.limit(10);
1234 * query.setOptions({ maxTimeMS: 1000 })
1235 * query.getOptions(); // { limit: 10, maxTimeMS: 1000 }
1236 *
1237 * @return {Object} the options
1238 * @api public
1239 */
1240
1241Query.prototype.getOptions = function() {
1242 return this.options;
1243};
1244
1245/**
1246 * Sets query options. Some options only make sense for certain operations.
1247 *
1248 * ####Options:
1249 *
1250 * The following options are only for `find()`:
1251 *
1252 * - [tailable](http://www.mongodb.org/display/DOCS/Tailable+Cursors)
1253 * - [sort](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsort(\)%7D%7D)
1254 * - [limit](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D)
1255 * - [skip](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D)
1256 * - [maxscan](https://docs.mongodb.org/v3.2/reference/operator/meta/maxScan/#metaOp._S_maxScan)
1257 * - [batchSize](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D)
1258 * - [comment](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment)
1259 * - [snapshot](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D)
1260 * - [readPreference](http://docs.mongodb.org/manual/applications/replication/#read-preference)
1261 * - [hint](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint)
1262 *
1263 * The following options are only for write operations: `update()`, `updateOne()`, `updateMany()`, `replaceOne()`, `findOneAndUpdate()`, and `findByIdAndUpdate()`:
1264 *
1265 * - [upsert](https://docs.mongodb.com/manual/reference/method/db.collection.update/)
1266 * - [writeConcern](https://docs.mongodb.com/manual/reference/method/db.collection.update/)
1267 * - [timestamps](https://mongoosejs.com/docs/guide.html#timestamps): If `timestamps` is set in the schema, set this option to `false` to skip timestamps for that particular update. Has no effect if `timestamps` is not enabled in the schema options.
1268 *
1269 * The following options are only for `find()`, `findOne()`, `findById()`, `findOneAndUpdate()`, and `findByIdAndUpdate()`:
1270 *
1271 * - [lean](./api.html#query_Query-lean)
1272 *
1273 * The following options are only for all operations **except** `update()`, `updateOne()`, `updateMany()`, `remove()`, `deleteOne()`, and `deleteMany()`:
1274 *
1275 * - [maxTimeMS](https://docs.mongodb.com/manual/reference/operator/meta/maxTimeMS/)
1276 *
1277 * The following options are for all operations:
1278 *
1279 * - [collation](https://docs.mongodb.com/manual/reference/collation/)
1280 * - [session](https://docs.mongodb.com/manual/reference/server-sessions/)
1281 *
1282 * @param {Object} options
1283 * @return {Query} this
1284 * @api public
1285 */
1286
1287Query.prototype.setOptions = function(options, overwrite) {
1288 // overwrite is only for internal use
1289 if (overwrite) {
1290 // ensure that _mongooseOptions & options are two different objects
1291 this._mongooseOptions = (options && utils.clone(options)) || {};
1292 this.options = options || {};
1293
1294 if ('populate' in options) {
1295 this.populate(this._mongooseOptions);
1296 }
1297 return this;
1298 }
1299
1300 if (options == null) {
1301 return this;
1302 }
1303 if (typeof options !== 'object') {
1304 throw new Error('Options must be an object, got "' + options + '"');
1305 }
1306
1307 if (Array.isArray(options.populate)) {
1308 const populate = options.populate;
1309 delete options.populate;
1310 const _numPopulate = populate.length;
1311 for (let i = 0; i < _numPopulate; ++i) {
1312 this.populate(populate[i]);
1313 }
1314 }
1315
1316 if ('useFindAndModify' in options) {
1317 this._mongooseOptions.useFindAndModify = options.useFindAndModify;
1318 delete options.useFindAndModify;
1319 }
1320 if ('omitUndefined' in options) {
1321 this._mongooseOptions.omitUndefined = options.omitUndefined;
1322 delete options.omitUndefined;
1323 }
1324
1325 return Query.base.setOptions.call(this, options);
1326};
1327
1328/**
1329 * Sets the [`explain` option](https://docs.mongodb.com/manual/reference/method/cursor.explain/),
1330 * which makes this query return detailed execution stats instead of the actual
1331 * query result. This method is useful for determining what index your queries
1332 * use.
1333 *
1334 * Calling `query.explain(v)` is equivalent to `query.setOption({ explain: v })`
1335 *
1336 * ####Example:
1337 *
1338 * const query = new Query();
1339 * const res = await query.find({ a: 1 }).explain('queryPlanner');
1340 * console.log(res);
1341 *
1342 * @param {String} [verbose] The verbosity mode. Either 'queryPlanner', 'executionStats', or 'allPlansExecution'. The default is 'queryPlanner'
1343 * @return {Query} this
1344 * @api public
1345 */
1346
1347Query.prototype.explain = function(verbose) {
1348 if (arguments.length === 0) {
1349 this.options.explain = true;
1350 return this;
1351 }
1352 this.options.explain = verbose;
1353 return this;
1354};
1355
1356/**
1357 * Sets the [maxTimeMS](https://docs.mongodb.com/manual/reference/method/cursor.maxTimeMS/)
1358 * option. This will tell the MongoDB server to abort if the query or write op
1359 * has been running for more than `ms` milliseconds.
1360 *
1361 * Calling `query.maxTimeMS(v)` is equivalent to `query.setOption({ maxTimeMS: v })`
1362 *
1363 * ####Example:
1364 *
1365 * const query = new Query();
1366 * // Throws an error 'operation exceeded time limit' as long as there's
1367 * // >= 1 doc in the queried collection
1368 * const res = await query.find({ $where: 'sleep(1000) || true' }).maxTimeMS(100);
1369 *
1370 * @param {Number} [ms] The number of milliseconds
1371 * @return {Query} this
1372 * @api public
1373 */
1374
1375Query.prototype.maxTimeMS = function(ms) {
1376 this.options.maxTimeMS = ms;
1377 return this;
1378};
1379
1380/**
1381 * Returns the current query conditions as a JSON object.
1382 *
1383 * ####Example:
1384 *
1385 * var query = new Query();
1386 * query.find({ a: 1 }).where('b').gt(2);
1387 * query.getQuery(); // { a: 1, b: { $gt: 2 } }
1388 *
1389 * @return {Object} current query conditions
1390 * @api public
1391 */
1392
1393Query.prototype.getQuery = function() {
1394 return this._conditions;
1395};
1396
1397/**
1398 * Sets the query conditions to the provided JSON object.
1399 *
1400 * ####Example:
1401 *
1402 * var query = new Query();
1403 * query.find({ a: 1 })
1404 * query.setQuery({ a: 2 });
1405 * query.getQuery(); // { a: 2 }
1406 *
1407 * @param {Object} new query conditions
1408 * @return {undefined}
1409 * @api public
1410 */
1411
1412Query.prototype.setQuery = function(val) {
1413 this._conditions = val;
1414};
1415
1416/**
1417 * Returns the current update operations as a JSON object.
1418 *
1419 * ####Example:
1420 *
1421 * var query = new Query();
1422 * query.update({}, { $set: { a: 5 } });
1423 * query.getUpdate(); // { $set: { a: 5 } }
1424 *
1425 * @return {Object} current update operations
1426 * @api public
1427 */
1428
1429Query.prototype.getUpdate = function() {
1430 return this._update;
1431};
1432
1433/**
1434 * Sets the current update operation to new value.
1435 *
1436 * ####Example:
1437 *
1438 * var query = new Query();
1439 * query.update({}, { $set: { a: 5 } });
1440 * query.setUpdate({ $set: { b: 6 } });
1441 * query.getUpdate(); // { $set: { b: 6 } }
1442 *
1443 * @param {Object} new update operation
1444 * @return {undefined}
1445 * @api public
1446 */
1447
1448Query.prototype.setUpdate = function(val) {
1449 this._update = val;
1450};
1451
1452/**
1453 * Returns fields selection for this query.
1454 *
1455 * @method _fieldsForExec
1456 * @return {Object}
1457 * @api private
1458 * @receiver Query
1459 */
1460
1461Query.prototype._fieldsForExec = function() {
1462 return utils.clone(this._fields);
1463};
1464
1465
1466/**
1467 * Return an update document with corrected $set operations.
1468 *
1469 * @method _updateForExec
1470 * @api private
1471 * @receiver Query
1472 */
1473
1474Query.prototype._updateForExec = function() {
1475 const update = utils.clone(this._update, {
1476 transform: false,
1477 depopulate: true
1478 });
1479 const ops = Object.keys(update);
1480 let i = ops.length;
1481 const ret = {};
1482
1483 while (i--) {
1484 const op = ops[i];
1485
1486 if (this.options.overwrite) {
1487 ret[op] = update[op];
1488 continue;
1489 }
1490
1491 if ('$' !== op[0]) {
1492 // fix up $set sugar
1493 if (!ret.$set) {
1494 if (update.$set) {
1495 ret.$set = update.$set;
1496 } else {
1497 ret.$set = {};
1498 }
1499 }
1500 ret.$set[op] = update[op];
1501 ops.splice(i, 1);
1502 if (!~ops.indexOf('$set')) ops.push('$set');
1503 } else if ('$set' === op) {
1504 if (!ret.$set) {
1505 ret[op] = update[op];
1506 }
1507 } else {
1508 ret[op] = update[op];
1509 }
1510 }
1511
1512 return ret;
1513};
1514
1515/**
1516 * Makes sure _path is set.
1517 *
1518 * @method _ensurePath
1519 * @param {String} method
1520 * @api private
1521 * @receiver Query
1522 */
1523
1524/**
1525 * Determines if `conds` can be merged using `mquery().merge()`
1526 *
1527 * @method canMerge
1528 * @memberOf Query
1529 * @instance
1530 * @param {Object} conds
1531 * @return {Boolean}
1532 * @api private
1533 */
1534
1535/**
1536 * Returns default options for this query.
1537 *
1538 * @param {Model} model
1539 * @api private
1540 */
1541
1542Query.prototype._optionsForExec = function(model) {
1543 const options = utils.clone(this.options);
1544
1545 delete options.populate;
1546 model = model || this.model;
1547
1548 if (!model) {
1549 return options;
1550 }
1551
1552 const safe = get(model, 'schema.options.safe', null);
1553 if (!('safe' in options) && safe != null) {
1554 setSafe(options, safe);
1555 }
1556
1557 // Apply schema-level `writeConcern` option
1558 applyWriteConcern(model.schema, options);
1559
1560 const readPreference = get(model, 'schema.options.read');
1561 if (!('readPreference' in options) && readPreference) {
1562 options.readPreference = readPreference;
1563 }
1564
1565 if (options.upsert !== void 0) {
1566 options.upsert = !!options.upsert;
1567 }
1568
1569 return options;
1570};
1571
1572/*!
1573 * ignore
1574 */
1575
1576const safeDeprecationWarning = 'Mongoose: the `safe` option is deprecated. ' +
1577 'Use write concerns instead: http://bit.ly/mongoose-w';
1578
1579const setSafe = util.deprecate(function setSafe(options, safe) {
1580 options.safe = safe;
1581}, safeDeprecationWarning);
1582
1583/**
1584 * Sets the lean option.
1585 *
1586 * Documents returned from queries with the `lean` option enabled are plain javascript objects, not [MongooseDocuments](#document-js). They have no `save` method, getters/setters or other Mongoose magic applied.
1587 *
1588 * ####Example:
1589 *
1590 * new Query().lean() // true
1591 * new Query().lean(true)
1592 * new Query().lean(false)
1593 *
1594 * Model.find().lean().exec(function (err, docs) {
1595 * docs[0] instanceof mongoose.Document // false
1596 * });
1597 *
1598 * This is a [great](https://groups.google.com/forum/#!topic/mongoose-orm/u2_DzDydcnA/discussion) option in high-performance read-only scenarios, especially when combined with [stream](#query_Query-stream).
1599 *
1600 * @param {Boolean|Object} bool defaults to true
1601 * @return {Query} this
1602 * @api public
1603 */
1604
1605Query.prototype.lean = function(v) {
1606 this._mongooseOptions.lean = arguments.length ? v : true;
1607 return this;
1608};
1609
1610/**
1611 * Adds a `$set` to this query's update without changing the operation.
1612 * This is useful for query middleware so you can add an update regardless
1613 * of whether you use `updateOne()`, `updateMany()`, `findOneAndUpdate()`, etc.
1614 *
1615 * ####Example:
1616 *
1617 * // Updates `{ $set: { updatedAt: new Date() } }`
1618 * new Query().updateOne({}, {}).set('updatedAt', new Date());
1619 * new Query().updateMany({}, {}).set({ updatedAt: new Date() });
1620 *
1621 * @param {String|Object} path path or object of key/value pairs to set
1622 * @param {Any} [val] the value to set
1623 * @return {Query} this
1624 * @api public
1625 */
1626
1627Query.prototype.set = function(path, val) {
1628 if (typeof path === 'object') {
1629 const keys = Object.keys(path);
1630 for (const key of keys) {
1631 this.set(key, path[key]);
1632 }
1633 return this;
1634 }
1635
1636 this._update = this._update || {};
1637 this._update.$set = this._update.$set || {};
1638 this._update.$set[path] = val;
1639 return this;
1640};
1641
1642/**
1643 * Gets/sets the error flag on this query. If this flag is not null or
1644 * undefined, the `exec()` promise will reject without executing.
1645 *
1646 * ####Example:
1647 *
1648 * Query().error(); // Get current error value
1649 * Query().error(null); // Unset the current error
1650 * Query().error(new Error('test')); // `exec()` will resolve with test
1651 * Schema.pre('find', function() {
1652 * if (!this.getQuery().userId) {
1653 * this.error(new Error('Not allowed to query without setting userId'));
1654 * }
1655 * });
1656 *
1657 * Note that query casting runs **after** hooks, so cast errors will override
1658 * custom errors.
1659 *
1660 * ####Example:
1661 * var TestSchema = new Schema({ num: Number });
1662 * var TestModel = db.model('Test', TestSchema);
1663 * TestModel.find({ num: 'not a number' }).error(new Error('woops')).exec(function(error) {
1664 * // `error` will be a cast error because `num` failed to cast
1665 * });
1666 *
1667 * @param {Error|null} err if set, `exec()` will fail fast before sending the query to MongoDB
1668 * @return {Query} this
1669 * @api public
1670 */
1671
1672Query.prototype.error = function error(err) {
1673 if (arguments.length === 0) {
1674 return this._error;
1675 }
1676
1677 this._error = err;
1678 return this;
1679};
1680
1681/*!
1682 * ignore
1683 */
1684
1685Query.prototype._unsetCastError = function _unsetCastError() {
1686 if (this._error != null && !(this._error instanceof CastError)) {
1687 return;
1688 }
1689 return this.error(null);
1690};
1691
1692/**
1693 * Getter/setter around the current mongoose-specific options for this query
1694 * Below are the current Mongoose-specific options.
1695 *
1696 * - `populate`: an array representing what paths will be populated. Should have one entry for each call to [`Query.prototype.populate()`](/docs/api.html#query_Query-populate)
1697 * - `lean`: if truthy, Mongoose will not [hydrate](/docs/api.html#model_Model.hydrate) any documents that are returned from this query. See [`Query.prototype.lean()`](/docs/api.html#query_Query-lean) for more information.
1698 * - `strict`: controls how Mongoose handles keys that aren't in the schema for updates. This option is `true` by default, which means Mongoose will silently strip any paths in the update that aren't in the schema. See the [`strict` mode docs](/docs/guide.html#strict) for more information.
1699 * - `strictQuery`: controls how Mongoose handles keys that aren't in the schema for the query `filter`. This option is `false` by default for backwards compatibility, which means Mongoose will allow `Model.find({ foo: 'bar' })` even if `foo` is not in the schema. See the [`strictQuery` docs](/docs/guide.html#strictQuery) for more information.
1700 * - `useFindAndModify`: used to work around the [`findAndModify()` deprecation warning](/docs/deprecations.html#-findandmodify-)
1701 * - `omitUndefined`: delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server.
1702 * - `nearSphere`: use `$nearSphere` instead of `near()`. See the [`Query.prototype.nearSphere()` docs](/docs/api.html#query_Query-nearSphere)
1703 *
1704 * Mongoose maintains a separate object for internal options because
1705 * Mongoose sends `Query.prototype.options` to the MongoDB server, and the
1706 * above options are not relevant for the MongoDB server.
1707 *
1708 * @param {Object} options if specified, overwrites the current options
1709 * @return {Object} the options
1710 * @api public
1711 */
1712
1713Query.prototype.mongooseOptions = function(v) {
1714 if (arguments.length > 0) {
1715 this._mongooseOptions = v;
1716 }
1717 return this._mongooseOptions;
1718};
1719
1720/*!
1721 * ignore
1722 */
1723
1724Query.prototype._castConditions = function() {
1725 try {
1726 this.cast(this.model);
1727 this._unsetCastError();
1728 } catch (err) {
1729 this.error(err);
1730 }
1731};
1732
1733/*!
1734 * ignore
1735 */
1736
1737function _castArrayFilters(query) {
1738 try {
1739 castArrayFilters(query);
1740 } catch (err) {
1741 query.error(err);
1742 }
1743}
1744
1745/**
1746 * Thunk around find()
1747 *
1748 * @param {Function} [callback]
1749 * @return {Query} this
1750 * @api private
1751 */
1752Query.prototype._find = wrapThunk(function(callback) {
1753 this._castConditions();
1754
1755 if (this.error() != null) {
1756 callback(this.error());
1757 return null;
1758 }
1759
1760 callback = _wrapThunkCallback(this, callback);
1761
1762 this._applyPaths();
1763 this._fields = this._castFields(this._fields);
1764
1765 const fields = this._fieldsForExec();
1766 const mongooseOptions = this._mongooseOptions;
1767 const _this = this;
1768 const userProvidedFields = _this._userProvidedFields || {};
1769
1770 // Separate options to pass down to `completeMany()` in case we need to
1771 // set a session on the document
1772 const completeManyOptions = Object.assign({}, {
1773 session: get(this, 'options.session', null)
1774 });
1775
1776 const cb = (err, docs) => {
1777 if (err) {
1778 return callback(err);
1779 }
1780
1781 if (docs.length === 0) {
1782 return callback(null, docs);
1783 }
1784 if (this.options.explain) {
1785 return callback(null, docs);
1786 }
1787
1788 if (!mongooseOptions.populate) {
1789 return mongooseOptions.lean ?
1790 callback(null, docs) :
1791 completeMany(_this.model, docs, fields, userProvidedFields, completeManyOptions, callback);
1792 }
1793
1794 const pop = helpers.preparePopulationOptionsMQ(_this, mongooseOptions);
1795 completeManyOptions.populated = pop;
1796 _this.model.populate(docs, pop, function(err, docs) {
1797 if (err) return callback(err);
1798 return mongooseOptions.lean ?
1799 callback(null, docs) :
1800 completeMany(_this.model, docs, fields, userProvidedFields, completeManyOptions, callback);
1801 });
1802 };
1803
1804 const options = this._optionsForExec();
1805 options.projection = this._fieldsForExec();
1806 const filter = this._conditions;
1807
1808 this._collection.find(filter, options, cb);
1809 return null;
1810});
1811
1812/**
1813 * Find all documents that match `selector`. The result will be an array of documents.
1814 *
1815 * If there are too many documents in the result to fit in memory, use
1816 * [`Query.prototype.cursor()`](api.html#query_Query-cursor)
1817 *
1818 * ####Example
1819 *
1820 * // Using async/await
1821 * const arr = await Movie.find({ year: { $gte: 1980, $lte: 1989 } });
1822 *
1823 * // Using callbacks
1824 * Movie.find({ year: { $gte: 1980, $lte: 1989 } }, function(err, arr) {});
1825 *
1826 * @param {Object} [filter] mongodb selector. If not specified, returns all documents.
1827 * @param {Function} [callback]
1828 * @return {Query} this
1829 * @api public
1830 */
1831
1832Query.prototype.find = function(conditions, callback) {
1833 if (typeof conditions === 'function') {
1834 callback = conditions;
1835 conditions = {};
1836 }
1837
1838 conditions = utils.toObject(conditions);
1839
1840 if (mquery.canMerge(conditions)) {
1841 this.merge(conditions);
1842
1843 prepareDiscriminatorCriteria(this);
1844 } else if (conditions != null) {
1845 this.error(new ObjectParameterError(conditions, 'filter', 'find'));
1846 }
1847
1848 // if we don't have a callback, then just return the query object
1849 if (!callback) {
1850 return Query.base.find.call(this);
1851 }
1852
1853 this._find(callback);
1854
1855 return this;
1856};
1857
1858/**
1859 * Merges another Query or conditions object into this one.
1860 *
1861 * When a Query is passed, conditions, field selection and options are merged.
1862 *
1863 * @param {Query|Object} source
1864 * @return {Query} this
1865 */
1866
1867Query.prototype.merge = function(source) {
1868 if (!source) {
1869 return this;
1870 }
1871
1872 const opts = { overwrite: true };
1873
1874 if (source instanceof Query) {
1875 // if source has a feature, apply it to ourselves
1876
1877 if (source._conditions) {
1878 utils.merge(this._conditions, source._conditions, opts);
1879 }
1880
1881 if (source._fields) {
1882 this._fields || (this._fields = {});
1883 utils.merge(this._fields, source._fields, opts);
1884 }
1885
1886 if (source.options) {
1887 this.options || (this.options = {});
1888 utils.merge(this.options, source.options, opts);
1889 }
1890
1891 if (source._update) {
1892 this._update || (this._update = {});
1893 utils.mergeClone(this._update, source._update);
1894 }
1895
1896 if (source._distinct) {
1897 this._distinct = source._distinct;
1898 }
1899
1900 return this;
1901 }
1902
1903 // plain object
1904 utils.merge(this._conditions, source, opts);
1905
1906 return this;
1907};
1908
1909/**
1910 * Adds a collation to this op (MongoDB 3.4 and up)
1911 *
1912 * @param {Object} value
1913 * @return {Query} this
1914 * @see MongoDB docs https://docs.mongodb.com/manual/reference/method/cursor.collation/#cursor.collation
1915 * @api public
1916 */
1917
1918Query.prototype.collation = function(value) {
1919 if (this.options == null) {
1920 this.options = {};
1921 }
1922 this.options.collation = value;
1923 return this;
1924};
1925
1926/**
1927 * Hydrate a single doc from `findOne()`, `findOneAndUpdate()`, etc.
1928 *
1929 * @api private
1930 */
1931
1932Query.prototype._completeOne = function(doc, res, callback) {
1933 if (!doc) {
1934 return callback(null, null);
1935 }
1936
1937 const model = this.model;
1938 const projection = utils.clone(this._fields);
1939 const userProvidedFields = this._userProvidedFields || {};
1940 // `populate`, `lean`
1941 const mongooseOptions = this._mongooseOptions;
1942 // `rawResult`
1943 const options = this.options;
1944
1945 if (options.explain) {
1946 return callback(null, doc);
1947 }
1948
1949 if (!mongooseOptions.populate) {
1950 return mongooseOptions.lean ?
1951 _completeOneLean(doc, res, options, callback) :
1952 completeOne(model, doc, res, options, projection, userProvidedFields,
1953 null, callback);
1954 }
1955
1956 const pop = helpers.preparePopulationOptionsMQ(this, this._mongooseOptions);
1957 model.populate(doc, pop, (err, doc) => {
1958 if (err) {
1959 return callback(err);
1960 }
1961 return mongooseOptions.lean ?
1962 _completeOneLean(doc, res, options, callback) :
1963 completeOne(model, doc, res, options, projection, userProvidedFields,
1964 pop, callback);
1965 });
1966};
1967
1968/**
1969 * Thunk around findOne()
1970 *
1971 * @param {Function} [callback]
1972 * @see findOne http://docs.mongodb.org/manual/reference/method/db.collection.findOne/
1973 * @api private
1974 */
1975
1976Query.prototype._findOne = wrapThunk(function(callback) {
1977 this._castConditions();
1978
1979 if (this.error()) {
1980 callback(this.error());
1981 return null;
1982 }
1983
1984 this._applyPaths();
1985 this._fields = this._castFields(this._fields);
1986
1987 // don't pass in the conditions because we already merged them in
1988 Query.base.findOne.call(this, {}, (err, doc) => {
1989 if (err) {
1990 callback(err);
1991 return null;
1992 }
1993
1994 this._completeOne(doc, null, _wrapThunkCallback(this, callback));
1995 });
1996});
1997
1998/**
1999 * Declares the query a findOne operation. When executed, the first found document is passed to the callback.
2000 *
2001 * Passing a `callback` executes the query. The result of the query is a single document.
2002 *
2003 * * *Note:* `conditions` is optional, and if `conditions` is null or undefined,
2004 * mongoose will send an empty `findOne` command to MongoDB, which will return
2005 * an arbitrary document. If you're querying by `_id`, use `Model.findById()`
2006 * instead.
2007 *
2008 * This function triggers the following middleware.
2009 *
2010 * - `findOne()`
2011 *
2012 * ####Example
2013 *
2014 * var query = Kitten.where({ color: 'white' });
2015 * query.findOne(function (err, kitten) {
2016 * if (err) return handleError(err);
2017 * if (kitten) {
2018 * // doc may be null if no document matched
2019 * }
2020 * });
2021 *
2022 * @param {Object} [filter] mongodb selector
2023 * @param {Object} [projection] optional fields to return
2024 * @param {Object} [options] see [`setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
2025 * @param {Function} [callback] optional params are (error, document)
2026 * @return {Query} this
2027 * @see findOne http://docs.mongodb.org/manual/reference/method/db.collection.findOne/
2028 * @see Query.select #query_Query-select
2029 * @api public
2030 */
2031
2032Query.prototype.findOne = function(conditions, projection, options, callback) {
2033 if (typeof conditions === 'function') {
2034 callback = conditions;
2035 conditions = null;
2036 projection = null;
2037 options = null;
2038 } else if (typeof projection === 'function') {
2039 callback = projection;
2040 options = null;
2041 projection = null;
2042 } else if (typeof options === 'function') {
2043 callback = options;
2044 options = null;
2045 }
2046
2047 // make sure we don't send in the whole Document to merge()
2048 conditions = utils.toObject(conditions);
2049
2050 this.op = 'findOne';
2051
2052 if (options) {
2053 this.setOptions(options);
2054 }
2055
2056 if (projection) {
2057 this.select(projection);
2058 }
2059
2060 if (mquery.canMerge(conditions)) {
2061 this.merge(conditions);
2062
2063 prepareDiscriminatorCriteria(this);
2064 } else if (conditions != null) {
2065 this.error(new ObjectParameterError(conditions, 'filter', 'findOne'));
2066 }
2067
2068 if (!callback) {
2069 // already merged in the conditions, don't need to send them in.
2070 return Query.base.findOne.call(this);
2071 }
2072
2073 this._findOne(callback);
2074
2075 return this;
2076};
2077
2078/**
2079 * Thunk around count()
2080 *
2081 * @param {Function} [callback]
2082 * @see count http://docs.mongodb.org/manual/reference/method/db.collection.count/
2083 * @api private
2084 */
2085
2086Query.prototype._count = wrapThunk(function(callback) {
2087 try {
2088 this.cast(this.model);
2089 } catch (err) {
2090 this.error(err);
2091 }
2092
2093 if (this.error()) {
2094 return callback(this.error());
2095 }
2096
2097 const conds = this._conditions;
2098 const options = this._optionsForExec();
2099
2100 this._collection.count(conds, options, utils.tick(callback));
2101});
2102
2103/**
2104 * Thunk around countDocuments()
2105 *
2106 * @param {Function} [callback]
2107 * @see countDocuments http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments
2108 * @api private
2109 */
2110
2111Query.prototype._countDocuments = wrapThunk(function(callback) {
2112 try {
2113 this.cast(this.model);
2114 } catch (err) {
2115 this.error(err);
2116 }
2117
2118 if (this.error()) {
2119 return callback(this.error());
2120 }
2121
2122 const conds = this._conditions;
2123 const options = this._optionsForExec();
2124
2125 this._collection.collection.countDocuments(conds, options, utils.tick(callback));
2126});
2127
2128/**
2129 * Thunk around estimatedDocumentCount()
2130 *
2131 * @param {Function} [callback]
2132 * @see estimatedDocumentCount http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#estimatedDocumentCount
2133 * @api private
2134 */
2135
2136Query.prototype._estimatedDocumentCount = wrapThunk(function(callback) {
2137 if (this.error()) {
2138 return callback(this.error());
2139 }
2140
2141 const options = this._optionsForExec();
2142
2143 this._collection.collection.estimatedDocumentCount(options, utils.tick(callback));
2144});
2145
2146/**
2147 * Specifies this query as a `count` query.
2148 *
2149 * This method is deprecated. If you want to count the number of documents in
2150 * a collection, e.g. `count({})`, use the [`estimatedDocumentCount()` function](/docs/api.html#query_Query-estimatedDocumentCount)
2151 * instead. Otherwise, use the [`countDocuments()`](/docs/api.html#query_Query-countDocuments) function instead.
2152 *
2153 * Passing a `callback` executes the query.
2154 *
2155 * This function triggers the following middleware.
2156 *
2157 * - `count()`
2158 *
2159 * ####Example:
2160 *
2161 * var countQuery = model.where({ 'color': 'black' }).count();
2162 *
2163 * query.count({ color: 'black' }).count(callback)
2164 *
2165 * query.count({ color: 'black' }, callback)
2166 *
2167 * query.where('color', 'black').count(function (err, count) {
2168 * if (err) return handleError(err);
2169 * console.log('there are %d kittens', count);
2170 * })
2171 *
2172 * @deprecated
2173 * @param {Object} [filter] count documents that match this object
2174 * @param {Function} [callback] optional params are (error, count)
2175 * @return {Query} this
2176 * @see count http://docs.mongodb.org/manual/reference/method/db.collection.count/
2177 * @api public
2178 */
2179
2180Query.prototype.count = function(filter, callback) {
2181 if (typeof filter === 'function') {
2182 callback = filter;
2183 filter = undefined;
2184 }
2185
2186 filter = utils.toObject(filter);
2187
2188 if (mquery.canMerge(filter)) {
2189 this.merge(filter);
2190 }
2191
2192 this.op = 'count';
2193 if (!callback) {
2194 return this;
2195 }
2196
2197 this._count(callback);
2198
2199 return this;
2200};
2201
2202/**
2203 * Specifies this query as a `estimatedDocumentCount()` query. Faster than
2204 * using `countDocuments()` for large collections because
2205 * `estimatedDocumentCount()` uses collection metadata rather than scanning
2206 * the entire collection.
2207 *
2208 * `estimatedDocumentCount()` does **not** accept a filter. `Model.find({ foo: bar }).estimatedDocumentCount()`
2209 * is equivalent to `Model.find().estimatedDocumentCount()`
2210 *
2211 * This function triggers the following middleware.
2212 *
2213 * - `estimatedDocumentCount()`
2214 *
2215 * ####Example:
2216 *
2217 * await Model.find().estimatedDocumentCount();
2218 *
2219 * @param {Object} [options] passed transparently to the [MongoDB driver](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#estimatedDocumentCount)
2220 * @param {Function} [callback] optional params are (error, count)
2221 * @return {Query} this
2222 * @see estimatedDocumentCount http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#estimatedDocumentCount
2223 * @api public
2224 */
2225
2226Query.prototype.estimatedDocumentCount = function(options, callback) {
2227 if (typeof options === 'function') {
2228 callback = options;
2229 options = undefined;
2230 }
2231
2232 if (typeof options === 'object' && options != null) {
2233 this.setOptions(options);
2234 }
2235
2236 this.op = 'estimatedDocumentCount';
2237 if (!callback) {
2238 return this;
2239 }
2240
2241 this._estimatedDocumentCount(callback);
2242
2243 return this;
2244};
2245
2246/**
2247 * Specifies this query as a `countDocuments()` query. Behaves like `count()`,
2248 * except it always does a full collection scan when passed an empty filter `{}`.
2249 *
2250 * There are also minor differences in how `countDocuments()` handles
2251 * [`$where` and a couple geospatial operators](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments).
2252 * versus `count()`.
2253 *
2254 * Passing a `callback` executes the query.
2255 *
2256 * This function triggers the following middleware.
2257 *
2258 * - `countDocuments()`
2259 *
2260 * ####Example:
2261 *
2262 * const countQuery = model.where({ 'color': 'black' }).countDocuments();
2263 *
2264 * query.countDocuments({ color: 'black' }).count(callback);
2265 *
2266 * query.countDocuments({ color: 'black' }, callback);
2267 *
2268 * query.where('color', 'black').countDocuments(function(err, count) {
2269 * if (err) return handleError(err);
2270 * console.log('there are %d kittens', count);
2271 * });
2272 *
2273 * The `countDocuments()` function is similar to `count()`, but there are a
2274 * [few operators that `countDocuments()` does not support](https://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments).
2275 * Below are the operators that `count()` supports but `countDocuments()` does not,
2276 * and the suggested replacement:
2277 *
2278 * - `$where`: [`$expr`](https://docs.mongodb.com/manual/reference/operator/query/expr/)
2279 * - `$near`: [`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/) with [`$center`](https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center)
2280 * - `$nearSphere`: [`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/) with [`$centerSphere`](https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere)
2281 *
2282 * @param {Object} [filter] mongodb selector
2283 * @param {Function} [callback] optional params are (error, count)
2284 * @return {Query} this
2285 * @see countDocuments http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments
2286 * @api public
2287 */
2288
2289Query.prototype.countDocuments = function(conditions, callback) {
2290 if (typeof conditions === 'function') {
2291 callback = conditions;
2292 conditions = undefined;
2293 }
2294
2295 conditions = utils.toObject(conditions);
2296
2297 if (mquery.canMerge(conditions)) {
2298 this.merge(conditions);
2299 }
2300
2301 this.op = 'countDocuments';
2302 if (!callback) {
2303 return this;
2304 }
2305
2306 this._countDocuments(callback);
2307
2308 return this;
2309};
2310
2311/**
2312 * Declares or executes a distict() operation.
2313 *
2314 * Passing a `callback` executes the query.
2315 *
2316 * This function does not trigger any middleware.
2317 *
2318 * ####Example
2319 *
2320 * distinct(field, conditions, callback)
2321 * distinct(field, conditions)
2322 * distinct(field, callback)
2323 * distinct(field)
2324 * distinct(callback)
2325 * distinct()
2326 *
2327 * @param {String} [field]
2328 * @param {Object|Query} [filter]
2329 * @param {Function} [callback] optional params are (error, arr)
2330 * @return {Query} this
2331 * @see distinct http://docs.mongodb.org/manual/reference/method/db.collection.distinct/
2332 * @api public
2333 */
2334
2335Query.prototype.distinct = function(field, conditions, callback) {
2336 if (!callback) {
2337 if (typeof conditions === 'function') {
2338 callback = conditions;
2339 conditions = undefined;
2340 } else if (typeof field === 'function') {
2341 callback = field;
2342 field = undefined;
2343 conditions = undefined;
2344 }
2345 }
2346
2347 conditions = utils.toObject(conditions);
2348
2349 if (mquery.canMerge(conditions)) {
2350 this.merge(conditions);
2351
2352 prepareDiscriminatorCriteria(this);
2353 } else if (conditions != null) {
2354 this.error(new ObjectParameterError(conditions, 'filter', 'distinct'));
2355 }
2356
2357 if (callback != null) {
2358 this._castConditions();
2359
2360 if (this.error() != null) {
2361 callback(this.error());
2362 return this;
2363 }
2364 }
2365
2366 return Query.base.distinct.call(this, {}, field, callback);
2367};
2368
2369/**
2370 * Sets the sort order
2371 *
2372 * If an object is passed, values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`.
2373 *
2374 * If a string is passed, it must be a space delimited list of path names. The
2375 * sort order of each path is ascending unless the path name is prefixed with `-`
2376 * which will be treated as descending.
2377 *
2378 * ####Example
2379 *
2380 * // sort by "field" ascending and "test" descending
2381 * query.sort({ field: 'asc', test: -1 });
2382 *
2383 * // equivalent
2384 * query.sort('field -test');
2385 *
2386 * ####Note
2387 *
2388 * Cannot be used with `distinct()`
2389 *
2390 * @param {Object|String} arg
2391 * @return {Query} this
2392 * @see cursor.sort http://docs.mongodb.org/manual/reference/method/cursor.sort/
2393 * @api public
2394 */
2395
2396Query.prototype.sort = function(arg) {
2397 if (arguments.length > 1) {
2398 throw new Error('sort() only takes 1 Argument');
2399 }
2400
2401 return Query.base.sort.call(this, arg);
2402};
2403
2404/**
2405 * Declare and/or execute this query as a remove() operation. `remove()` is
2406 * deprecated, you should use [`deleteOne()`](#query_Query-deleteOne)
2407 * or [`deleteMany()`](#query_Query-deleteMany) instead.
2408 *
2409 * This function does not trigger any middleware
2410 *
2411 * ####Example
2412 *
2413 * Character.remove({ name: /Stark/ }, callback);
2414 *
2415 * This function calls the MongoDB driver's [`Collection#remove()` function](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#remove).
2416 * The returned [promise](https://mongoosejs.com/docs/queries.html) resolves to an
2417 * object that contains 3 properties:
2418 *
2419 * - `ok`: `1` if no errors occurred
2420 * - `deletedCount`: the number of documents deleted
2421 * - `n`: the number of documents deleted. Equal to `deletedCount`.
2422 *
2423 * ####Example
2424 *
2425 * const res = await Character.remove({ name: /Stark/ });
2426 * // Number of docs deleted
2427 * res.deletedCount;
2428 *
2429 * ####Note
2430 *
2431 * Calling `remove()` creates a [Mongoose query](./queries.html), and a query
2432 * does not execute until you either pass a callback, call [`Query#then()`](#query_Query-then),
2433 * or call [`Query#exec()`](#query_Query-exec).
2434 *
2435 * // not executed
2436 * const query = Character.remove({ name: /Stark/ });
2437 *
2438 * // executed
2439 * Character.remove({ name: /Stark/ }, callback);
2440 * Character.remove({ name: /Stark/ }).remove(callback);
2441 *
2442 * // executed without a callback
2443 * Character.exec();
2444 *
2445 * @param {Object|Query} [filter] mongodb selector
2446 * @param {Function} [callback] optional params are (error, mongooseDeleteResult)
2447 * @return {Query} this
2448 * @deprecated
2449 * @see deleteWriteOpResult http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~deleteWriteOpResult
2450 * @see MongoDB driver remove http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#remove
2451 * @api public
2452 */
2453
2454Query.prototype.remove = function(filter, callback) {
2455 if (typeof filter === 'function') {
2456 callback = filter;
2457 filter = null;
2458 }
2459
2460 filter = utils.toObject(filter);
2461
2462 if (mquery.canMerge(filter)) {
2463 this.merge(filter);
2464
2465 prepareDiscriminatorCriteria(this);
2466 } else if (filter != null) {
2467 this.error(new ObjectParameterError(filter, 'filter', 'remove'));
2468 }
2469
2470 if (!callback) {
2471 return Query.base.remove.call(this);
2472 }
2473
2474 this._remove(callback);
2475 return this;
2476};
2477
2478/*!
2479 * ignore
2480 */
2481
2482Query.prototype._remove = wrapThunk(function(callback) {
2483 this._castConditions();
2484
2485 if (this.error() != null) {
2486 callback(this.error());
2487 return this;
2488 }
2489
2490 callback = _wrapThunkCallback(this, callback);
2491
2492 return Query.base.remove.call(this, helpers.handleDeleteWriteOpResult(callback));
2493});
2494
2495/**
2496 * Declare and/or execute this query as a `deleteOne()` operation. Works like
2497 * remove, except it deletes at most one document regardless of the `single`
2498 * option.
2499 *
2500 * This function does not trigger any middleware.
2501 *
2502 * ####Example
2503 *
2504 * Character.deleteOne({ name: 'Eddard Stark' }, callback);
2505 * Character.deleteOne({ name: 'Eddard Stark' }).then(next);
2506 *
2507 * This function calls the MongoDB driver's [`Collection#deleteOne()` function](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteOne).
2508 * The returned [promise](https://mongoosejs.com/docs/queries.html) resolves to an
2509 * object that contains 3 properties:
2510 *
2511 * - `ok`: `1` if no errors occurred
2512 * - `deletedCount`: the number of documents deleted
2513 * - `n`: the number of documents deleted. Equal to `deletedCount`.
2514 *
2515 * ####Example
2516 *
2517 * const res = await Character.deleteOne({ name: 'Eddard Stark' });
2518 * // `1` if MongoDB deleted a doc, `0` if no docs matched the filter `{ name: ... }`
2519 * res.deletedCount;
2520 *
2521 * @param {Object|Query} [filter] mongodb selector
2522 * @param {Function} [callback] optional params are (error, mongooseDeleteResult)
2523 * @return {Query} this
2524 * @see deleteWriteOpResult http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~deleteWriteOpResult
2525 * @see MongoDB Driver deleteOne http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteOne
2526 * @api public
2527 */
2528
2529Query.prototype.deleteOne = function(filter, callback) {
2530 if (typeof filter === 'function') {
2531 callback = filter;
2532 filter = null;
2533 }
2534
2535 filter = utils.toObject(filter);
2536
2537 if (mquery.canMerge(filter)) {
2538 this.merge(filter);
2539
2540 prepareDiscriminatorCriteria(this);
2541 } else if (filter != null) {
2542 this.error(new ObjectParameterError(filter, 'filter', 'deleteOne'));
2543 }
2544
2545 if (!callback) {
2546 return Query.base.deleteOne.call(this);
2547 }
2548
2549 this._deleteOne.call(this, callback);
2550
2551 return this;
2552};
2553
2554/*!
2555 * Internal thunk for `deleteOne()`
2556 */
2557
2558Query.prototype._deleteOne = wrapThunk(function(callback) {
2559 this._castConditions();
2560
2561 if (this.error() != null) {
2562 callback(this.error());
2563 return this;
2564 }
2565
2566 callback = _wrapThunkCallback(this, callback);
2567
2568 return Query.base.deleteOne.call(this, helpers.handleDeleteWriteOpResult(callback));
2569});
2570
2571/**
2572 * Declare and/or execute this query as a `deleteMany()` operation. Works like
2573 * remove, except it deletes _every_ document that matches `criteria` in the
2574 * collection, regardless of the value of `single`.
2575 *
2576 * This function does not trigger any middleware
2577 *
2578 * ####Example
2579 *
2580 * Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }, callback)
2581 * Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }).then(next)
2582 *
2583 * This function calls the MongoDB driver's [`Collection#deleteOne()` function](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteMany).
2584 * The returned [promise](https://mongoosejs.com/docs/queries.html) resolves to an
2585 * object that contains 3 properties:
2586 *
2587 * - `ok`: `1` if no errors occurred
2588 * - `deletedCount`: the number of documents deleted
2589 * - `n`: the number of documents deleted. Equal to `deletedCount`.
2590 *
2591 * ####Example
2592 *
2593 * const res = await Character.deleteMany({ name: /Stark/, age: { $gte: 18 } });
2594 * // `0` if no docs matched the filter, number of docs deleted otherwise
2595 * res.deletedCount;
2596 *
2597 * @param {Object|Query} [filter] mongodb selector
2598 * @param {Function} [callback] optional params are (error, mongooseDeleteResult)
2599 * @return {Query} this
2600 * @see deleteWriteOpResult http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~deleteWriteOpResult
2601 * @see MongoDB Driver deleteMany http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteMany
2602 * @api public
2603 */
2604
2605Query.prototype.deleteMany = function(filter, callback) {
2606 if (typeof filter === 'function') {
2607 callback = filter;
2608 filter = null;
2609 }
2610
2611 filter = utils.toObject(filter);
2612
2613 if (mquery.canMerge(filter)) {
2614 this.merge(filter);
2615
2616 prepareDiscriminatorCriteria(this);
2617 } else if (filter != null) {
2618 this.error(new ObjectParameterError(filter, 'filter', 'deleteMany'));
2619 }
2620
2621 if (!callback) {
2622 return Query.base.deleteMany.call(this);
2623 }
2624
2625 this._deleteMany.call(this, callback);
2626
2627 return this;
2628};
2629
2630/*!
2631 * Internal thunk around `deleteMany()`
2632 */
2633
2634Query.prototype._deleteMany = wrapThunk(function(callback) {
2635 this._castConditions();
2636
2637 if (this.error() != null) {
2638 callback(this.error());
2639 return this;
2640 }
2641
2642 callback = _wrapThunkCallback(this, callback);
2643
2644 return Query.base.deleteMany.call(this, helpers.handleDeleteWriteOpResult(callback));
2645});
2646
2647/*!
2648 * hydrates a document
2649 *
2650 * @param {Model} model
2651 * @param {Document} doc
2652 * @param {Object} res 3rd parameter to callback
2653 * @param {Object} fields
2654 * @param {Query} self
2655 * @param {Array} [pop] array of paths used in population
2656 * @param {Function} callback
2657 */
2658
2659function completeOne(model, doc, res, options, fields, userProvidedFields, pop, callback) {
2660 const opts = pop ?
2661 {populated: pop}
2662 : undefined;
2663
2664 const casted = helpers.createModel(model, doc, fields, userProvidedFields);
2665 try {
2666 casted.init(doc, opts, _init);
2667 } catch (error) {
2668 _init(error);
2669 }
2670
2671 function _init(err) {
2672 if (err) {
2673 return process.nextTick(() => callback(err));
2674 }
2675
2676 casted.$session(options.session);
2677
2678 if (options.rawResult) {
2679 res.value = casted;
2680 return process.nextTick(() => callback(null, res));
2681 }
2682 process.nextTick(() => callback(null, casted));
2683 }
2684}
2685
2686/*!
2687 * If the model is a discriminator type and not root, then add the key & value to the criteria.
2688 */
2689
2690function prepareDiscriminatorCriteria(query) {
2691 if (!query || !query.model || !query.model.schema) {
2692 return;
2693 }
2694
2695 const schema = query.model.schema;
2696
2697 if (schema && schema.discriminatorMapping && !schema.discriminatorMapping.isRoot) {
2698 query._conditions[schema.discriminatorMapping.key] = schema.discriminatorMapping.value;
2699 }
2700}
2701
2702/**
2703 * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) update command.
2704 *
2705 * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes immediately if `callback` is passed.
2706 *
2707 * This function triggers the following middleware.
2708 *
2709 * - `findOneAndUpdate()`
2710 *
2711 * ####Available options
2712 *
2713 * - `new`: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0)
2714 * - `upsert`: bool - creates the object if it doesn't exist. defaults to false.
2715 * - `fields`: {Object|String} - Field selection. Equivalent to `.select(fields).findOneAndUpdate()`
2716 * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
2717 * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
2718 * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema.
2719 * - `setDefaultsOnInsert`: if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/).
2720 * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
2721 * - `context` (string) if set to 'query' and `runValidators` is on, `this` will refer to the query in custom validator functions that update validation runs. Does nothing if `runValidators` is false.
2722 *
2723 * ####Callback Signature
2724 * function(error, doc) {
2725 * // error: any errors that occurred
2726 * // doc: the document before updates are applied if `new: false`, or after updates if `new = true`
2727 * }
2728 *
2729 * ####Examples
2730 *
2731 * query.findOneAndUpdate(conditions, update, options, callback) // executes
2732 * query.findOneAndUpdate(conditions, update, options) // returns Query
2733 * query.findOneAndUpdate(conditions, update, callback) // executes
2734 * query.findOneAndUpdate(conditions, update) // returns Query
2735 * query.findOneAndUpdate(update, callback) // returns Query
2736 * query.findOneAndUpdate(update) // returns Query
2737 * query.findOneAndUpdate(callback) // executes
2738 * query.findOneAndUpdate() // returns Query
2739 *
2740 * @method findOneAndUpdate
2741 * @memberOf Query
2742 * @instance
2743 * @param {Object|Query} [query]
2744 * @param {Object} [doc]
2745 * @param {Object} [options]
2746 * @param {Boolean} [options.rawResult] if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
2747 * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
2748 * @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors.
2749 * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](http://mongoosejs.com/docs/api.html#query_Query-lean).
2750 * @param {Function} [callback] optional params are (error, doc), _unless_ `rawResult` is used, in which case params are (error, writeOpResult)
2751 * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command
2752 * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult
2753 * @return {Query} this
2754 * @api public
2755 */
2756
2757Query.prototype.findOneAndUpdate = function(criteria, doc, options, callback) {
2758 this.op = 'findOneAndUpdate';
2759 this._validate();
2760
2761 switch (arguments.length) {
2762 case 3:
2763 if (typeof options === 'function') {
2764 callback = options;
2765 options = {};
2766 }
2767 break;
2768 case 2:
2769 if (typeof doc === 'function') {
2770 callback = doc;
2771 doc = criteria;
2772 criteria = undefined;
2773 }
2774 options = undefined;
2775 break;
2776 case 1:
2777 if (typeof criteria === 'function') {
2778 callback = criteria;
2779 criteria = options = doc = undefined;
2780 } else {
2781 doc = criteria;
2782 criteria = options = undefined;
2783 }
2784 }
2785
2786 if (mquery.canMerge(criteria)) {
2787 this.merge(criteria);
2788 }
2789
2790 // apply doc
2791 if (doc) {
2792 this._mergeUpdate(doc);
2793 }
2794
2795 if (options) {
2796 options = utils.clone(options);
2797 if (options.projection) {
2798 this.select(options.projection);
2799 delete options.projection;
2800 }
2801 if (options.fields) {
2802 this.select(options.fields);
2803 delete options.fields;
2804 }
2805
2806 this.setOptions(options);
2807 }
2808
2809 if (!callback) {
2810 return this;
2811 }
2812
2813 this._findOneAndUpdate(callback);
2814
2815 return this;
2816};
2817
2818/*!
2819 * Thunk around findOneAndUpdate()
2820 *
2821 * @param {Function} [callback]
2822 * @api private
2823 */
2824
2825Query.prototype._findOneAndUpdate = wrapThunk(function(callback) {
2826 if (this.error() != null) {
2827 return callback(this.error());
2828 }
2829
2830 this._findAndModify('update', callback);
2831});
2832
2833/**
2834 * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) remove command.
2835 *
2836 * Finds a matching document, removes it, passing the found document (if any) to the callback. Executes immediately if `callback` is passed.
2837 *
2838 * This function triggers the following middleware.
2839 *
2840 * - `findOneAndRemove()`
2841 *
2842 * ####Available options
2843 *
2844 * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
2845 * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
2846 * - `rawResult`: if true, resolves to the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
2847 *
2848 * ####Callback Signature
2849 * function(error, doc) {
2850 * // error: any errors that occurred
2851 * // doc: the document before updates are applied if `new: false`, or after updates if `new = true`
2852 * }
2853 *
2854 * ####Examples
2855 *
2856 * A.where().findOneAndRemove(conditions, options, callback) // executes
2857 * A.where().findOneAndRemove(conditions, options) // return Query
2858 * A.where().findOneAndRemove(conditions, callback) // executes
2859 * A.where().findOneAndRemove(conditions) // returns Query
2860 * A.where().findOneAndRemove(callback) // executes
2861 * A.where().findOneAndRemove() // returns Query
2862 *
2863 * @method findOneAndRemove
2864 * @memberOf Query
2865 * @instance
2866 * @param {Object} [conditions]
2867 * @param {Object} [options]
2868 * @param {Boolean} [options.rawResult] if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
2869 * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
2870 * @param {Function} [callback] optional params are (error, document)
2871 * @return {Query} this
2872 * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command
2873 * @api public
2874 */
2875
2876Query.prototype.findOneAndRemove = function(conditions, options, callback) {
2877 this.op = 'findOneAndRemove';
2878 this._validate();
2879
2880 switch (arguments.length) {
2881 case 2:
2882 if (typeof options === 'function') {
2883 callback = options;
2884 options = {};
2885 }
2886 break;
2887 case 1:
2888 if (typeof conditions === 'function') {
2889 callback = conditions;
2890 conditions = undefined;
2891 options = undefined;
2892 }
2893 break;
2894 }
2895
2896 if (mquery.canMerge(conditions)) {
2897 this.merge(conditions);
2898 }
2899
2900 options && this.setOptions(options);
2901
2902 if (!callback) {
2903 return this;
2904 }
2905
2906 this._findOneAndRemove(callback);
2907
2908 return this;
2909};
2910
2911/**
2912 * Issues a MongoDB [findOneAndDelete](https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndDelete/) command.
2913 *
2914 * Finds a matching document, removes it, and passes the found document (if any) to the callback. Executes immediately if `callback` is passed.
2915 *
2916 * This function triggers the following middleware.
2917 *
2918 * - `findOneAndDelete()`
2919 *
2920 * This function differs slightly from `Model.findOneAndRemove()` in that
2921 * `findOneAndRemove()` becomes a [MongoDB `findAndModify()` command](https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/),
2922 * as opposed to a `findOneAndDelete()` command. For most mongoose use cases,
2923 * this distinction is purely pedantic. You should use `findOneAndDelete()`
2924 * unless you have a good reason not to.
2925 *
2926 * ####Available options
2927 *
2928 * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
2929 * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
2930 * - `rawResult`: if true, resolves to the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
2931 *
2932 * ####Callback Signature
2933 * function(error, doc) {
2934 * // error: any errors that occurred
2935 * // doc: the document before updates are applied if `new: false`, or after updates if `new = true`
2936 * }
2937 *
2938 * ####Examples
2939 *
2940 * A.where().findOneAndDelete(conditions, options, callback) // executes
2941 * A.where().findOneAndDelete(conditions, options) // return Query
2942 * A.where().findOneAndDelete(conditions, callback) // executes
2943 * A.where().findOneAndDelete(conditions) // returns Query
2944 * A.where().findOneAndDelete(callback) // executes
2945 * A.where().findOneAndDelete() // returns Query
2946 *
2947 * @method findOneAndDelete
2948 * @memberOf Query
2949 * @param {Object} [conditions]
2950 * @param {Object} [options]
2951 * @param {Boolean} [options.rawResult] if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
2952 * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
2953 * @param {Function} [callback] optional params are (error, document)
2954 * @return {Query} this
2955 * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command
2956 * @api public
2957 */
2958
2959Query.prototype.findOneAndDelete = function(conditions, options, callback) {
2960 this.op = 'findOneAndDelete';
2961 this._validate();
2962
2963 switch (arguments.length) {
2964 case 2:
2965 if (typeof options === 'function') {
2966 callback = options;
2967 options = {};
2968 }
2969 break;
2970 case 1:
2971 if (typeof conditions === 'function') {
2972 callback = conditions;
2973 conditions = undefined;
2974 options = undefined;
2975 }
2976 break;
2977 }
2978
2979 if (mquery.canMerge(conditions)) {
2980 this.merge(conditions);
2981 }
2982
2983 options && this.setOptions(options);
2984
2985 if (!callback) {
2986 return this;
2987 }
2988
2989 this._findOneAndDelete(callback);
2990
2991 return this;
2992};
2993
2994/*!
2995 * Thunk around findOneAndDelete()
2996 *
2997 * @param {Function} [callback]
2998 * @return {Query} this
2999 * @api private
3000 */
3001Query.prototype._findOneAndDelete = wrapThunk(function(callback) {
3002 this._castConditions();
3003
3004 if (this.error() != null) {
3005 callback(this.error());
3006 return null;
3007 }
3008
3009 const filter = this._conditions;
3010 const options = this._optionsForExec();
3011 let fields = null;
3012
3013 if (this._fields != null) {
3014 options.projection = this._castFields(utils.clone(this._fields));
3015 fields = options.projection;
3016 if (fields instanceof Error) {
3017 callback(fields);
3018 return null;
3019 }
3020 }
3021
3022 this._collection.collection.findOneAndDelete(filter, options, _wrapThunkCallback(this, (err, res) => {
3023 if (err) {
3024 return callback(err);
3025 }
3026
3027 const doc = res.value;
3028
3029 return this._completeOne(doc, res, callback);
3030 }));
3031});
3032
3033/**
3034 * Issues a MongoDB [findOneAndReplace](https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndReplace/) command.
3035 *
3036 * Finds a matching document, removes it, and passes the found document (if any) to the callback. Executes immediately if `callback` is passed.
3037 *
3038 * This function triggers the following middleware.
3039 *
3040 * - `findOneAndReplace()`
3041 *
3042 * ####Available options
3043 *
3044 * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
3045 * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
3046 * - `rawResult`: if true, resolves to the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
3047 *
3048 * ####Callback Signature
3049 * function(error, doc) {
3050 * // error: any errors that occurred
3051 * // doc: the document before updates are applied if `new: false`, or after updates if `new = true`
3052 * }
3053 *
3054 * ####Examples
3055 *
3056 * A.where().findOneAndReplace(conditions, options, callback) // executes
3057 * A.where().findOneAndReplace(conditions, options) // return Query
3058 * A.where().findOneAndReplace(conditions, callback) // executes
3059 * A.where().findOneAndReplace(conditions) // returns Query
3060 * A.where().findOneAndReplace(callback) // executes
3061 * A.where().findOneAndReplace() // returns Query
3062 *
3063 * @method findOneAndReplace
3064 * @memberOf Query
3065 * @param {Object} [conditions]
3066 * @param {Object} [options]
3067 * @param {Boolean} [options.rawResult] if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
3068 * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
3069 * @param {Function} [callback] optional params are (error, document)
3070 * @return {Query} this
3071 * @api public
3072 */
3073
3074Query.prototype.findOneAndReplace = function(conditions, options, callback) {
3075 this.op = 'findOneAndReplace';
3076 this._validate();
3077
3078 switch (arguments.length) {
3079 case 2:
3080 if (typeof options === 'function') {
3081 callback = options;
3082 options = {};
3083 }
3084 break;
3085 case 1:
3086 if (typeof conditions === 'function') {
3087 callback = conditions;
3088 conditions = undefined;
3089 options = undefined;
3090 }
3091 break;
3092 }
3093
3094 if (mquery.canMerge(conditions)) {
3095 this.merge(conditions);
3096 }
3097
3098 options && this.setOptions(options);
3099
3100 if (!callback) {
3101 return this;
3102 }
3103
3104 this._findOneAndReplace(callback);
3105
3106 return this;
3107};
3108
3109/*!
3110 * Thunk around findOneAndReplace()
3111 *
3112 * @param {Function} [callback]
3113 * @return {Query} this
3114 * @api private
3115 */
3116Query.prototype._findOneAndReplace = wrapThunk(function(callback) {
3117 this._castConditions();
3118
3119 if (this.error() != null) {
3120 callback(this.error());
3121 return null;
3122 }
3123
3124 const filter = this._conditions;
3125 const options = this._optionsForExec();
3126 let fields = null;
3127
3128 if (this._fields != null) {
3129 options.projection = this._castFields(utils.clone(this._fields));
3130 fields = options.projection;
3131 if (fields instanceof Error) {
3132 callback(fields);
3133 return null;
3134 }
3135 }
3136
3137 this._collection.collection.findOneAndReplace(filter, options, (err, res) => {
3138 if (err) {
3139 return callback(err);
3140 }
3141
3142 const doc = res.value;
3143
3144 return this._completeOne(doc, res, callback);
3145 });
3146});
3147
3148/*!
3149 * Thunk around findOneAndRemove()
3150 *
3151 * @param {Function} [callback]
3152 * @return {Query} this
3153 * @api private
3154 */
3155Query.prototype._findOneAndRemove = wrapThunk(function(callback) {
3156 if (this.error() != null) {
3157 callback(this.error());
3158 return;
3159 }
3160
3161 this._findAndModify('remove', callback);
3162});
3163
3164/*!
3165 * Get options from query opts, falling back to the base mongoose object.
3166 */
3167
3168function _getOption(query, option, def) {
3169 const opts = query._optionsForExec(query.model);
3170
3171 if (option in opts) {
3172 return opts[option];
3173 }
3174 if (option in query.model.base.options) {
3175 return query.model.base.options[option];
3176 }
3177 return def;
3178}
3179
3180/*!
3181 * Override mquery.prototype._findAndModify to provide casting etc.
3182 *
3183 * @param {String} type - either "remove" or "update"
3184 * @param {Function} callback
3185 * @api private
3186 */
3187
3188Query.prototype._findAndModify = function(type, callback) {
3189 if (typeof callback !== 'function') {
3190 throw new Error('Expected callback in _findAndModify');
3191 }
3192
3193 const model = this.model;
3194 const schema = model.schema;
3195 const _this = this;
3196 let castedDoc = this._update;
3197 let fields;
3198 let doValidate;
3199
3200 const castedQuery = castQuery(this);
3201 if (castedQuery instanceof Error) {
3202 return callback(castedQuery);
3203 }
3204
3205 _castArrayFilters(this);
3206
3207 const opts = this._optionsForExec(model);
3208
3209 if ('strict' in opts) {
3210 this._mongooseOptions.strict = opts.strict;
3211 }
3212
3213 const isOverwriting = this.options.overwrite && !hasDollarKeys(castedDoc);
3214 if (isOverwriting) {
3215 castedDoc = new this.model(castedDoc, null, true);
3216 }
3217
3218 if (type === 'remove') {
3219 opts.remove = true;
3220 } else {
3221 if (!('new' in opts)) {
3222 opts.new = false;
3223 }
3224 if (!('upsert' in opts)) {
3225 opts.upsert = false;
3226 }
3227 if (opts.upsert || opts['new']) {
3228 opts.remove = false;
3229 }
3230
3231 if (isOverwriting) {
3232 doValidate = function(callback) {
3233 castedDoc.validate(callback);
3234 };
3235 } else {
3236 castedDoc = castDoc(this, opts.overwrite);
3237 castedDoc = setDefaultsOnInsert(this._conditions, schema, castedDoc, opts);
3238 if (!castedDoc) {
3239 if (opts.upsert) {
3240 // still need to do the upsert to empty doc
3241 const doc = utils.clone(castedQuery);
3242 delete doc._id;
3243 castedDoc = {$set: doc};
3244 } else {
3245 this.findOne(callback);
3246 return this;
3247 }
3248 } else if (castedDoc instanceof Error) {
3249 return callback(castedDoc);
3250 } else {
3251 // In order to make MongoDB 2.6 happy (see
3252 // https://jira.mongodb.org/browse/SERVER-12266 and related issues)
3253 // if we have an actual update document but $set is empty, junk the $set.
3254 if (castedDoc.$set && Object.keys(castedDoc.$set).length === 0) {
3255 delete castedDoc.$set;
3256 }
3257 }
3258
3259 doValidate = updateValidators(this, schema, castedDoc, opts);
3260 }
3261 }
3262
3263 this._applyPaths();
3264
3265 const options = this._mongooseOptions;
3266
3267 if (this._fields) {
3268 fields = utils.clone(this._fields);
3269 opts.projection = this._castFields(fields);
3270 if (opts.projection instanceof Error) {
3271 return callback(opts.projection);
3272 }
3273 }
3274
3275 if (opts.sort) convertSortToArray(opts);
3276
3277 const cb = function(err, doc, res) {
3278 if (err) {
3279 return callback(err);
3280 }
3281
3282 _this._completeOne(doc, res, callback);
3283 };
3284
3285 let _callback;
3286
3287 let useFindAndModify = true;
3288 const runValidators = _getOption(this, 'runValidators', false);
3289 const base = _this.model && _this.model.base;
3290 const conn = get(model, 'collection.conn', {});
3291 if ('useFindAndModify' in base.options) {
3292 useFindAndModify = base.get('useFindAndModify');
3293 }
3294 if ('useFindAndModify' in conn.config) {
3295 useFindAndModify = conn.config.useFindAndModify;
3296 }
3297 if ('useFindAndModify' in options) {
3298 useFindAndModify = options.useFindAndModify;
3299 }
3300 if (useFindAndModify === false) {
3301 // Bypass mquery
3302 const collection = _this._collection.collection;
3303 if ('new' in opts) {
3304 opts.returnOriginal = !opts['new'];
3305 delete opts['new'];
3306 }
3307
3308 if (type === 'remove') {
3309 collection.findOneAndDelete(castedQuery, opts, _wrapThunkCallback(_this, function(error, res) {
3310 return cb(error, res ? res.value : res, res);
3311 }));
3312
3313 return this;
3314 }
3315
3316 // honors legacy overwrite option for backward compatibility
3317 const updateMethod = isOverwriting ? 'findOneAndReplace' : 'findOneAndUpdate';
3318
3319 if (runValidators && doValidate) {
3320 _callback = function(error) {
3321 if (error) {
3322 return callback(error);
3323 }
3324 if (castedDoc && castedDoc.toBSON) {
3325 castedDoc = castedDoc.toBSON();
3326 }
3327
3328 collection[updateMethod](castedQuery, castedDoc, opts, _wrapThunkCallback(_this, function(error, res) {
3329 return cb(error, res ? res.value : res, res);
3330 }));
3331 };
3332
3333 try {
3334 doValidate(_callback);
3335 } catch (error) {
3336 callback(error);
3337 }
3338 } else {
3339 if (castedDoc && castedDoc.toBSON) {
3340 castedDoc = castedDoc.toBSON();
3341 }
3342 collection[updateMethod](castedQuery, castedDoc, opts, _wrapThunkCallback(_this, function(error, res) {
3343 return cb(error, res ? res.value : res, res);
3344 }));
3345 }
3346
3347 return this;
3348 }
3349
3350 if (runValidators && doValidate) {
3351 _callback = function(error) {
3352 if (error) {
3353 return callback(error);
3354 }
3355 if (castedDoc && castedDoc.toBSON) {
3356 castedDoc = castedDoc.toBSON();
3357 }
3358 _this._collection.findAndModify(castedQuery, castedDoc, opts, _wrapThunkCallback(_this, function(error, res) {
3359 return cb(error, res ? res.value : res, res);
3360 }));
3361 };
3362
3363 try {
3364 doValidate(_callback);
3365 } catch (error) {
3366 callback(error);
3367 }
3368 } else {
3369 if (castedDoc && castedDoc.toBSON) {
3370 castedDoc = castedDoc.toBSON();
3371 }
3372 this._collection.findAndModify(castedQuery, castedDoc, opts, _wrapThunkCallback(_this, function(error, res) {
3373 return cb(error, res ? res.value : res, res);
3374 }));
3375 }
3376
3377 return this;
3378};
3379
3380/*!
3381 * ignore
3382 */
3383
3384function _completeOneLean(doc, res, opts, callback) {
3385 if (opts.rawResult) {
3386 return callback(null, res);
3387 }
3388 return callback(null, doc);
3389}
3390
3391/*!
3392 * Override mquery.prototype._mergeUpdate to handle mongoose objects in
3393 * updates.
3394 *
3395 * @param {Object} doc
3396 * @api private
3397 */
3398
3399Query.prototype._mergeUpdate = function(doc) {
3400 if (!this._update) this._update = {};
3401 if (doc instanceof Query) {
3402 if (doc._update) {
3403 utils.mergeClone(this._update, doc._update);
3404 }
3405 } else {
3406 utils.mergeClone(this._update, doc);
3407 }
3408};
3409
3410/*!
3411 * The mongodb driver 1.3.23 only supports the nested array sort
3412 * syntax. We must convert it or sorting findAndModify will not work.
3413 */
3414
3415function convertSortToArray(opts) {
3416 if (Array.isArray(opts.sort)) {
3417 return;
3418 }
3419 if (!utils.isObject(opts.sort)) {
3420 return;
3421 }
3422
3423 const sort = [];
3424
3425 for (const key in opts.sort) {
3426 if (utils.object.hasOwnProperty(opts.sort, key)) {
3427 sort.push([key, opts.sort[key]]);
3428 }
3429 }
3430
3431 opts.sort = sort;
3432}
3433
3434/*!
3435 * ignore
3436 */
3437
3438function _updateThunk(op, callback) {
3439 const schema = this.model.schema;
3440 let doValidate;
3441 const _this = this;
3442
3443 this._castConditions();
3444
3445 _castArrayFilters(this);
3446
3447 if (this.error() != null) {
3448 callback(this.error());
3449 return null;
3450 }
3451
3452 callback = _wrapThunkCallback(this, callback);
3453
3454 const castedQuery = this._conditions;
3455 let castedDoc;
3456 const options = this._optionsForExec(this.model);
3457
3458 ++this._executionCount;
3459
3460 this._update = utils.clone(this._update, options);
3461 const isOverwriting = this.options.overwrite && !hasDollarKeys(this._update);
3462 if (isOverwriting) {
3463 castedDoc = new this.model(this._update, null, true);
3464 } else {
3465 castedDoc = castDoc(this, options.overwrite);
3466
3467 if (castedDoc instanceof Error) {
3468 callback(castedDoc);
3469 return null;
3470 }
3471
3472 if (castedDoc == null || Object.keys(castedDoc).length === 0) {
3473 callback(null, 0);
3474 return null;
3475 }
3476
3477 castedDoc = setDefaultsOnInsert(this._conditions, this.model.schema,
3478 castedDoc, options);
3479 }
3480
3481 const runValidators = _getOption(this, 'runValidators', false);
3482 if (runValidators) {
3483 if (isOverwriting) {
3484 doValidate = function(callback) {
3485 castedDoc.validate(callback);
3486 };
3487 } else {
3488 doValidate = updateValidators(this, schema, castedDoc, options);
3489 }
3490 const _callback = function(err) {
3491 if (err) {
3492 return callback(err);
3493 }
3494
3495 if (castedDoc.toBSON) {
3496 castedDoc = castedDoc.toBSON();
3497 }
3498 _this._collection[op](castedQuery, castedDoc, options, callback);
3499 };
3500 try {
3501 doValidate(_callback);
3502 } catch (err) {
3503 process.nextTick(function() {
3504 callback(err);
3505 });
3506 }
3507 return null;
3508 }
3509
3510 if (castedDoc.toBSON) {
3511 castedDoc = castedDoc.toBSON();
3512 }
3513
3514 this._collection[op](castedQuery, castedDoc, options, callback);
3515 return null;
3516}
3517
3518/*!
3519 * Internal thunk for .update()
3520 *
3521 * @param {Function} callback
3522 * @see Model.update #model_Model.update
3523 * @api private
3524 */
3525Query.prototype._execUpdate = wrapThunk(function(callback) {
3526 return _updateThunk.call(this, 'update', callback);
3527});
3528
3529/*!
3530 * Internal thunk for .updateMany()
3531 *
3532 * @param {Function} callback
3533 * @see Model.update #model_Model.update
3534 * @api private
3535 */
3536Query.prototype._updateMany = wrapThunk(function(callback) {
3537 return _updateThunk.call(this, 'updateMany', callback);
3538});
3539
3540/*!
3541 * Internal thunk for .updateOne()
3542 *
3543 * @param {Function} callback
3544 * @see Model.update #model_Model.update
3545 * @api private
3546 */
3547Query.prototype._updateOne = wrapThunk(function(callback) {
3548 return _updateThunk.call(this, 'updateOne', callback);
3549});
3550
3551/*!
3552 * Internal thunk for .replaceOne()
3553 *
3554 * @param {Function} callback
3555 * @see Model.replaceOne #model_Model.replaceOne
3556 * @api private
3557 */
3558Query.prototype._replaceOne = wrapThunk(function(callback) {
3559 return _updateThunk.call(this, 'replaceOne', callback);
3560});
3561
3562/**
3563 * Declare and/or execute this query as an update() operation.
3564 *
3565 * _All paths passed that are not $atomic operations will become $set ops._
3566 *
3567 * This function triggers the following middleware.
3568 *
3569 * - `update()`
3570 *
3571 * ####Example
3572 *
3573 * Model.where({ _id: id }).update({ title: 'words' })
3574 *
3575 * // becomes
3576 *
3577 * Model.where({ _id: id }).update({ $set: { title: 'words' }})
3578 *
3579 * ####Valid options:
3580 *
3581 * - `upsert` (boolean) whether to create the doc if it doesn't match (false)
3582 * - `multi` (boolean) whether multiple documents should be updated (false)
3583 * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema.
3584 * - `setDefaultsOnInsert`: if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/).
3585 * - `strict` (boolean) overrides the `strict` option for this update
3586 * - `overwrite` (boolean) disables update-only mode, allowing you to overwrite the doc (false)
3587 * - `context` (string) if set to 'query' and `runValidators` is on, `this` will refer to the query in custom validator functions that update validation runs. Does nothing if `runValidators` is false.
3588 * - `read`
3589 * - `writeConcern`
3590 *
3591 * ####Note
3592 *
3593 * Passing an empty object `{}` as the doc will result in a no-op unless the `overwrite` option is passed. Without the `overwrite` option set, the update operation will be ignored and the callback executed without sending the command to MongoDB so as to prevent accidently overwritting documents in the collection.
3594 *
3595 * ####Note
3596 *
3597 * The operation is only executed when a callback is passed. To force execution without a callback, we must first call update() and then execute it by using the `exec()` method.
3598 *
3599 * var q = Model.where({ _id: id });
3600 * q.update({ $set: { name: 'bob' }}).update(); // not executed
3601 *
3602 * q.update({ $set: { name: 'bob' }}).exec(); // executed
3603 *
3604 * // keys that are not $atomic ops become $set.
3605 * // this executes the same command as the previous example.
3606 * q.update({ name: 'bob' }).exec();
3607 *
3608 * // overwriting with empty docs
3609 * var q = Model.where({ _id: id }).setOptions({ overwrite: true })
3610 * q.update({ }, callback); // executes
3611 *
3612 * // multi update with overwrite to empty doc
3613 * var q = Model.where({ _id: id });
3614 * q.setOptions({ multi: true, overwrite: true })
3615 * q.update({ });
3616 * q.update(callback); // executed
3617 *
3618 * // multi updates
3619 * Model.where()
3620 * .update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, callback)
3621 *
3622 * // more multi updates
3623 * Model.where()
3624 * .setOptions({ multi: true })
3625 * .update({ $set: { arr: [] }}, callback)
3626 *
3627 * // single update by default
3628 * Model.where({ email: 'address@example.com' })
3629 * .update({ $inc: { counter: 1 }}, callback)
3630 *
3631 * API summary
3632 *
3633 * update(criteria, doc, options, cb) // executes
3634 * update(criteria, doc, options)
3635 * update(criteria, doc, cb) // executes
3636 * update(criteria, doc)
3637 * update(doc, cb) // executes
3638 * update(doc)
3639 * update(cb) // executes
3640 * update(true) // executes
3641 * update()
3642 *
3643 * @param {Object} [criteria]
3644 * @param {Object} [doc] the update command
3645 * @param {Object} [options]
3646 * @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors.
3647 * @param {Function} [callback] optional, params are (error, writeOpResult)
3648 * @return {Query} this
3649 * @see Model.update #model_Model.update
3650 * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/
3651 * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult
3652 * @api public
3653 */
3654
3655Query.prototype.update = function(conditions, doc, options, callback) {
3656 if (typeof options === 'function') {
3657 // .update(conditions, doc, callback)
3658 callback = options;
3659 options = null;
3660 } else if (typeof doc === 'function') {
3661 // .update(doc, callback);
3662 callback = doc;
3663 doc = conditions;
3664 conditions = {};
3665 options = null;
3666 } else if (typeof conditions === 'function') {
3667 // .update(callback)
3668 callback = conditions;
3669 conditions = undefined;
3670 doc = undefined;
3671 options = undefined;
3672 } else if (typeof conditions === 'object' && !doc && !options && !callback) {
3673 // .update(doc)
3674 doc = conditions;
3675 conditions = undefined;
3676 options = undefined;
3677 callback = undefined;
3678 }
3679
3680 return _update(this, 'update', conditions, doc, options, callback);
3681};
3682
3683/**
3684 * Declare and/or execute this query as an updateMany() operation. Same as
3685 * `update()`, except MongoDB will update _all_ documents that match
3686 * `criteria` (as opposed to just the first one) regardless of the value of
3687 * the `multi` option.
3688 *
3689 * **Note** updateMany will _not_ fire update middleware. Use `pre('updateMany')`
3690 * and `post('updateMany')` instead.
3691 *
3692 * This function triggers the following middleware.
3693 *
3694 * - `updateMany()`
3695 *
3696 * @param {Object} [criteria]
3697 * @param {Object} [doc] the update command
3698 * @param {Object} [options]
3699 @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors.
3700 * @param {Function} [callback] optional params are (error, writeOpResult)
3701 * @return {Query} this
3702 * @see Model.update #model_Model.update
3703 * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/
3704 * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult
3705 * @api public
3706 */
3707
3708Query.prototype.updateMany = function(conditions, doc, options, callback) {
3709 if (typeof options === 'function') {
3710 // .update(conditions, doc, callback)
3711 callback = options;
3712 options = null;
3713 } else if (typeof doc === 'function') {
3714 // .update(doc, callback);
3715 callback = doc;
3716 doc = conditions;
3717 conditions = {};
3718 options = null;
3719 } else if (typeof conditions === 'function') {
3720 // .update(callback)
3721 callback = conditions;
3722 conditions = undefined;
3723 doc = undefined;
3724 options = undefined;
3725 } else if (typeof conditions === 'object' && !doc && !options && !callback) {
3726 // .update(doc)
3727 doc = conditions;
3728 conditions = undefined;
3729 options = undefined;
3730 callback = undefined;
3731 }
3732
3733 return _update(this, 'updateMany', conditions, doc, options, callback);
3734};
3735
3736/**
3737 * Declare and/or execute this query as an updateOne() operation. Same as
3738 * `update()`, except it does not support the `multi` or `overwrite` options.
3739 *
3740 * - MongoDB will update _only_ the first document that matches `criteria` regardless of the value of the `multi` option.
3741 * - Use `replaceOne()` if you want to overwrite an entire document rather than using atomic operators like `$set`.
3742 *
3743 * **Note** updateOne will _not_ fire update middleware. Use `pre('updateOne')`
3744 * and `post('updateOne')` instead.
3745 *
3746 * This function triggers the following middleware.
3747 *
3748 * - `updateOne()`
3749 *
3750 * @param {Object} [criteria]
3751 * @param {Object} [doc] the update command
3752 * @param {Object} [options]
3753 @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors.
3754 * @param {Function} [callback] params are (error, writeOpResult)
3755 * @return {Query} this
3756 * @see Model.update #model_Model.update
3757 * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/
3758 * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult
3759 * @api public
3760 */
3761
3762Query.prototype.updateOne = function(conditions, doc, options, callback) {
3763 if (typeof options === 'function') {
3764 // .update(conditions, doc, callback)
3765 callback = options;
3766 options = null;
3767 } else if (typeof doc === 'function') {
3768 // .update(doc, callback);
3769 callback = doc;
3770 doc = conditions;
3771 conditions = {};
3772 options = null;
3773 } else if (typeof conditions === 'function') {
3774 // .update(callback)
3775 callback = conditions;
3776 conditions = undefined;
3777 doc = undefined;
3778 options = undefined;
3779 } else if (typeof conditions === 'object' && !doc && !options && !callback) {
3780 // .update(doc)
3781 doc = conditions;
3782 conditions = undefined;
3783 options = undefined;
3784 callback = undefined;
3785 }
3786
3787 return _update(this, 'updateOne', conditions, doc, options, callback);
3788};
3789
3790/**
3791 * Declare and/or execute this query as a replaceOne() operation. Same as
3792 * `update()`, except MongoDB will replace the existing document and will
3793 * not accept any atomic operators (`$set`, etc.)
3794 *
3795 * **Note** replaceOne will _not_ fire update middleware. Use `pre('replaceOne')`
3796 * and `post('replaceOne')` instead.
3797 *
3798 * This function triggers the following middleware.
3799 *
3800 * - `replaceOne()`
3801 *
3802 * @param {Object} [criteria]
3803 * @param {Object} [doc] the update command
3804 * @param {Object} [options]
3805 * @param {Function} [callback] optional params are (error, writeOpResult)
3806 * @return {Query} this
3807 * @see Model.update #model_Model.update
3808 * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/
3809 * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult
3810 * @api public
3811 */
3812
3813Query.prototype.replaceOne = function(conditions, doc, options, callback) {
3814 if (typeof options === 'function') {
3815 // .update(conditions, doc, callback)
3816 callback = options;
3817 options = null;
3818 } else if (typeof doc === 'function') {
3819 // .update(doc, callback);
3820 callback = doc;
3821 doc = conditions;
3822 conditions = {};
3823 options = null;
3824 } else if (typeof conditions === 'function') {
3825 // .update(callback)
3826 callback = conditions;
3827 conditions = undefined;
3828 doc = undefined;
3829 options = undefined;
3830 } else if (typeof conditions === 'object' && !doc && !options && !callback) {
3831 // .update(doc)
3832 doc = conditions;
3833 conditions = undefined;
3834 options = undefined;
3835 callback = undefined;
3836 }
3837
3838 this.setOptions({ overwrite: true });
3839 return _update(this, 'replaceOne', conditions, doc, options, callback);
3840};
3841
3842/*!
3843 * Internal helper for update, updateMany, updateOne, replaceOne
3844 */
3845
3846function _update(query, op, filter, doc, options, callback) {
3847 // make sure we don't send in the whole Document to merge()
3848 query.op = op;
3849 filter = utils.toObject(filter);
3850 doc = doc || {};
3851
3852 const oldCb = callback;
3853 if (oldCb) {
3854 if (typeof oldCb === 'function') {
3855 callback = function(error, result) {
3856 oldCb(error, result ? result.result : {ok: 0, n: 0, nModified: 0});
3857 };
3858 } else {
3859 throw new Error('Invalid callback() argument.');
3860 }
3861 }
3862
3863 // strict is an option used in the update checking, make sure it gets set
3864 if (options) {
3865 if ('strict' in options) {
3866 query._mongooseOptions.strict = options.strict;
3867 }
3868 }
3869
3870 if (!(filter instanceof Query) &&
3871 filter != null &&
3872 filter.toString() !== '[object Object]') {
3873 query.error(new ObjectParameterError(filter, 'filter', op));
3874 } else {
3875 query.merge(filter);
3876 }
3877
3878 if (utils.isObject(options)) {
3879 query.setOptions(options);
3880 }
3881
3882 query._mergeUpdate(doc);
3883
3884 // Hooks
3885 if (callback) {
3886 if (op === 'update') {
3887 query._execUpdate(callback);
3888 return query;
3889 }
3890 query['_' + op](callback);
3891 return query;
3892 }
3893
3894 return Query.base[op].call(query, filter, doc, options, callback);
3895}
3896
3897/**
3898 * Runs a function `fn` and treats the return value of `fn` as the new value
3899 * for the query to resolve to.
3900 *
3901 * Any functions you pass to `map()` will run **after** any post hooks.
3902 *
3903 * ####Example:
3904 *
3905 * const res = await MyModel.findOne().map(res => {
3906 * // Sets a `loadedAt` property on the doc that tells you the time the
3907 * // document was loaded.
3908 * return res == null ?
3909 * res :
3910 * Object.assign(res, { loadedAt: new Date() });
3911 * });
3912 *
3913 * @method map
3914 * @memberOf Query
3915 * @instance
3916 * @param {Function} fn function to run to transform the query result
3917 * @return {Query} this
3918 */
3919
3920Query.prototype.map = function(fn) {
3921 this._transforms.push(fn);
3922 return this;
3923};
3924
3925/**
3926 * Make this query throw an error if no documents match the given `filter`.
3927 * This is handy for integrating with async/await, because `orFail()` saves you
3928 * an extra `if` statement to check if no document was found.
3929 *
3930 * ####Example:
3931 *
3932 * // Throws if no doc returned
3933 * await Model.findOne({ foo: 'bar' }).orFail();
3934 *
3935 * // Throws if no document was updated
3936 * await Model.updateOne({ foo: 'bar' }, { name: 'test' }).orFail();
3937 *
3938 * // Throws "No docs found!" error if no docs match `{ foo: 'bar' }`
3939 * await Model.find({ foo: 'bar' }).orFail(new Error('No docs found!'));
3940 *
3941 * // Throws "Not found" error if no document was found
3942 * await Model.findOneAndUpdate({ foo: 'bar' }, { name: 'test' }).
3943 * orFail(() => Error('Not found'));
3944 *
3945 * @method orFail
3946 * @memberOf Query
3947 * @instance
3948 * @param {Function|Error} [err] optional error to throw if no docs match `filter`. If not specified, `orFail()` will throw a `DocumentNotFoundError`
3949 * @return {Query} this
3950 */
3951
3952Query.prototype.orFail = function(err) {
3953 this.map(res => {
3954 switch (this.op) {
3955 case 'find':
3956 if (res.length === 0) {
3957 throw _orFailError(err, this);
3958 }
3959 break;
3960 case 'findOne':
3961 if (res == null) {
3962 throw _orFailError(err, this);
3963 }
3964 break;
3965 case 'update':
3966 case 'updateMany':
3967 case 'updateOne':
3968 if (get(res, 'result.nModified') === 0) {
3969 throw _orFailError(err, this);
3970 }
3971 break;
3972 case 'findOneAndDelete':
3973 if (get(res, 'lastErrorObject.n') === 0) {
3974 throw _orFailError(err, this);
3975 }
3976 break;
3977 case 'findOneAndUpdate':
3978 if (get(res, 'lastErrorObject.updatedExisting') === false) {
3979 throw _orFailError(err, this);
3980 }
3981 break;
3982 case 'deleteMany':
3983 case 'deleteOne':
3984 case 'remove':
3985 if (res.n === 0) {
3986 throw _orFailError(err, this);
3987 }
3988 break;
3989 default:
3990 break;
3991 }
3992
3993 return res;
3994 });
3995 return this;
3996};
3997
3998/*!
3999 * Get the error to throw for `orFail()`
4000 */
4001
4002function _orFailError(err, query) {
4003 if (typeof err === 'function') {
4004 err = err.call(query);
4005 }
4006
4007 if (err == null) {
4008 err = new DocumentNotFoundError(query.getQuery());
4009 }
4010
4011 return err;
4012}
4013
4014/**
4015 * Executes the query
4016 *
4017 * ####Examples:
4018 *
4019 * var promise = query.exec();
4020 * var promise = query.exec('update');
4021 *
4022 * query.exec(callback);
4023 * query.exec('find', callback);
4024 *
4025 * @param {String|Function} [operation]
4026 * @param {Function} [callback] optional params depend on the function being called
4027 * @return {Promise}
4028 * @api public
4029 */
4030
4031Query.prototype.exec = function exec(op, callback) {
4032 const _this = this;
4033
4034 if (typeof op === 'function') {
4035 callback = op;
4036 op = null;
4037 } else if (typeof op === 'string') {
4038 this.op = op;
4039 }
4040
4041 if (callback != null) {
4042 callback = this.model.$wrapCallback(callback);
4043 }
4044
4045 return utils.promiseOrCallback(callback, (cb) => {
4046 if (!_this.op) {
4047 cb();
4048 return;
4049 }
4050
4051 this._hooks.execPre('exec', this, [], (error) => {
4052 if (error) {
4053 return cb(error);
4054 }
4055 this[this.op].call(this, (error, res) => {
4056 if (error) {
4057 return cb(error);
4058 }
4059
4060 this._hooks.execPost('exec', this, [], {}, (error) => {
4061 if (error) {
4062 return cb(error);
4063 }
4064
4065 cb(null, res);
4066 });
4067 });
4068 });
4069 }, this.model.events);
4070};
4071
4072/*!
4073 * ignore
4074 */
4075
4076function _wrapThunkCallback(query, cb) {
4077 return function(error, res) {
4078 if (error != null) {
4079 return cb(error);
4080 }
4081
4082 for (const fn of query._transforms) {
4083 try {
4084 res = fn(res);
4085 } catch (error) {
4086 return cb(error);
4087 }
4088 }
4089
4090 return cb(null, res);
4091 };
4092}
4093
4094/**
4095 * Executes the query returning a `Promise` which will be
4096 * resolved with either the doc(s) or rejected with the error.
4097 *
4098 * @param {Function} [resolve]
4099 * @param {Function} [reject]
4100 * @return {Promise}
4101 * @api public
4102 */
4103
4104Query.prototype.then = function(resolve, reject) {
4105 return this.exec().then(resolve, reject);
4106};
4107
4108/**
4109 * Executes the query returning a `Promise` which will be
4110 * resolved with either the doc(s) or rejected with the error.
4111 * Like `.then()`, but only takes a rejection handler.
4112 *
4113 * @param {Function} [reject]
4114 * @return {Promise}
4115 * @api public
4116 */
4117
4118Query.prototype.catch = function(reject) {
4119 return this.exec().then(null, reject);
4120};
4121
4122/*!
4123 * ignore
4124 */
4125
4126Query.prototype._pre = function(fn) {
4127 this._hooks.pre('exec', fn);
4128 return this;
4129};
4130
4131/*!
4132 * ignore
4133 */
4134
4135Query.prototype._post = function(fn) {
4136 this._hooks.post('exec', fn);
4137 return this;
4138};
4139
4140/*!
4141 * Casts obj for an update command.
4142 *
4143 * @param {Object} obj
4144 * @return {Object} obj after casting its values
4145 * @api private
4146 */
4147
4148Query.prototype._castUpdate = function _castUpdate(obj, overwrite) {
4149 let strict;
4150 if ('strict' in this._mongooseOptions) {
4151 strict = this._mongooseOptions.strict;
4152 } else if (this.schema && this.schema.options) {
4153 strict = this.schema.options.strict;
4154 } else {
4155 strict = true;
4156 }
4157
4158 let omitUndefined = false;
4159 if ('omitUndefined' in this._mongooseOptions) {
4160 omitUndefined = this._mongooseOptions.omitUndefined;
4161 }
4162
4163 let useNestedStrict;
4164 if ('useNestedStrict' in this.options) {
4165 useNestedStrict = this.options.useNestedStrict;
4166 }
4167
4168 return castUpdate(this.schema, obj, {
4169 overwrite: overwrite,
4170 strict: strict,
4171 omitUndefined,
4172 useNestedStrict: useNestedStrict
4173 }, this, this._conditions);
4174};
4175
4176/*!
4177 * castQuery
4178 * @api private
4179 */
4180
4181function castQuery(query) {
4182 try {
4183 return query.cast(query.model);
4184 } catch (err) {
4185 return err;
4186 }
4187}
4188
4189/*!
4190 * castDoc
4191 * @api private
4192 */
4193
4194function castDoc(query, overwrite) {
4195 try {
4196 return query._castUpdate(query._update, overwrite);
4197 } catch (err) {
4198 return err;
4199 }
4200}
4201
4202/**
4203 * Specifies paths which should be populated with other documents.
4204 *
4205 * ####Example:
4206 *
4207 * Kitten.findOne().populate('owner').exec(function (err, kitten) {
4208 * console.log(kitten.owner.name) // Max
4209 * })
4210 *
4211 * Kitten.find().populate({
4212 * path: 'owner'
4213 * , select: 'name'
4214 * , match: { color: 'black' }
4215 * , options: { sort: { name: -1 }}
4216 * }).exec(function (err, kittens) {
4217 * console.log(kittens[0].owner.name) // Zoopa
4218 * })
4219 *
4220 * // alternatively
4221 * Kitten.find().populate('owner', 'name', null, {sort: { name: -1 }}).exec(function (err, kittens) {
4222 * console.log(kittens[0].owner.name) // Zoopa
4223 * })
4224 *
4225 * Paths are populated after the query executes and a response is received. A separate query is then executed for each path specified for population. After a response for each query has also been returned, the results are passed to the callback.
4226 *
4227 * @param {Object|String} path either the path to populate or an object specifying all parameters
4228 * @param {Object|String} [select] Field selection for the population query
4229 * @param {Model} [model] The model you wish to use for population. If not specified, populate will look up the model by the name in the Schema's `ref` field.
4230 * @param {Object} [match] Conditions for the population query
4231 * @param {Object} [options] Options for the population query (sort, etc)
4232 * @see population ./populate.html
4233 * @see Query#select #query_Query-select
4234 * @see Model.populate #model_Model.populate
4235 * @return {Query} this
4236 * @api public
4237 */
4238
4239Query.prototype.populate = function() {
4240 if (arguments.length === 0) {
4241 return this;
4242 }
4243
4244 const res = utils.populate.apply(null, arguments);
4245
4246 // Propagate readConcern and readPreference and lean from parent query,
4247 // unless one already specified
4248 if (this.options != null) {
4249 const readConcern = this.options.readConcern;
4250 const readPref = this.options.readPreference;
4251
4252 for (let i = 0; i < res.length; ++i) {
4253 if (readConcern != null && get(res[i], 'options.readConcern') == null) {
4254 res[i].options = res[i].options || {};
4255 res[i].options.readConcern = readConcern;
4256 }
4257 if (readPref != null && get(res[i], 'options.readPreference') == null) {
4258 res[i].options = res[i].options || {};
4259 res[i].options.readPreference = readPref;
4260 }
4261 }
4262 }
4263
4264 const opts = this._mongooseOptions;
4265
4266 if (opts.lean != null) {
4267 const lean = opts.lean;
4268 for (let i = 0; i < res.length; ++i) {
4269 if (get(res[i], 'options.lean') == null) {
4270 res[i].options = res[i].options || {};
4271 res[i].options.lean = lean;
4272 }
4273 }
4274 }
4275
4276 if (!utils.isObject(opts.populate)) {
4277 opts.populate = {};
4278 }
4279
4280 const pop = opts.populate;
4281
4282 for (let i = 0; i < res.length; ++i) {
4283 const path = res[i].path;
4284 if (pop[path] && pop[path].populate && res[i].populate) {
4285 res[i].populate = pop[path].populate.concat(res[i].populate);
4286 }
4287 pop[res[i].path] = res[i];
4288 }
4289
4290 return this;
4291};
4292
4293/**
4294 * Gets a list of paths to be populated by this query
4295 *
4296 * ####Example:
4297 * bookSchema.pre('findOne', function() {
4298 * let keys = this.getPopulatedPaths(); // ['author']
4299 * })
4300 * ...
4301 * Book.findOne({}).populate('author')
4302 *
4303 * @return {Array} an array of strings representing populated paths
4304 * @api public
4305 */
4306
4307Query.prototype.getPopulatedPaths = function getPopulatedPaths() {
4308 const obj = this._mongooseOptions.populate || {};
4309 return Object.keys(obj);
4310};
4311
4312/**
4313 * Casts this query to the schema of `model`
4314 *
4315 * ####Note
4316 *
4317 * If `obj` is present, it is cast instead of this query.
4318 *
4319 * @param {Model} [model] the model to cast to. If not set, defaults to `this.model`
4320 * @param {Object} [obj]
4321 * @return {Object}
4322 * @api public
4323 */
4324
4325Query.prototype.cast = function(model, obj) {
4326 obj || (obj = this._conditions);
4327
4328 model = model || this.model;
4329
4330 try {
4331 return cast(model.schema, obj, {
4332 upsert: this.options && this.options.upsert,
4333 strict: (this.options && 'strict' in this.options) ?
4334 this.options.strict :
4335 get(model, 'schema.options.strict', null),
4336 strictQuery: (this.options && this.options.strictQuery) ||
4337 get(model, 'schema.options.strictQuery', null)
4338 }, this);
4339 } catch (err) {
4340 // CastError, assign model
4341 if (typeof err.setModel === 'function') {
4342 err.setModel(model);
4343 }
4344 throw err;
4345 }
4346};
4347
4348/**
4349 * Casts selected field arguments for field selection with mongo 2.2
4350 *
4351 * query.select({ ids: { $elemMatch: { $in: [hexString] }})
4352 *
4353 * @param {Object} fields
4354 * @see https://github.com/Automattic/mongoose/issues/1091
4355 * @see http://docs.mongodb.org/manual/reference/projection/elemMatch/
4356 * @api private
4357 */
4358
4359Query.prototype._castFields = function _castFields(fields) {
4360 let selected,
4361 elemMatchKeys,
4362 keys,
4363 key,
4364 out,
4365 i;
4366
4367 if (fields) {
4368 keys = Object.keys(fields);
4369 elemMatchKeys = [];
4370 i = keys.length;
4371
4372 // collect $elemMatch args
4373 while (i--) {
4374 key = keys[i];
4375 if (fields[key].$elemMatch) {
4376 selected || (selected = {});
4377 selected[key] = fields[key];
4378 elemMatchKeys.push(key);
4379 }
4380 }
4381 }
4382
4383 if (selected) {
4384 // they passed $elemMatch, cast em
4385 try {
4386 out = this.cast(this.model, selected);
4387 } catch (err) {
4388 return err;
4389 }
4390
4391 // apply the casted field args
4392 i = elemMatchKeys.length;
4393 while (i--) {
4394 key = elemMatchKeys[i];
4395 fields[key] = out[key];
4396 }
4397 }
4398
4399 return fields;
4400};
4401
4402/**
4403 * Applies schematype selected options to this query.
4404 * @api private
4405 */
4406
4407Query.prototype._applyPaths = function applyPaths() {
4408 this._fields = this._fields || {};
4409 helpers.applyPaths(this._fields, this.model.schema);
4410
4411 let _selectPopulatedPaths = true;
4412
4413 if ('selectPopulatedPaths' in this.model.base.options) {
4414 _selectPopulatedPaths = this.model.base.options.selectPopulatedPaths;
4415 }
4416 if ('selectPopulatedPaths' in this.model.schema.options) {
4417 _selectPopulatedPaths = this.model.schema.options.selectPopulatedPaths;
4418 }
4419
4420 if (_selectPopulatedPaths) {
4421 selectPopulatedFields(this);
4422 }
4423};
4424
4425/**
4426 * Returns a wrapper around a [mongodb driver cursor](http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html).
4427 * A QueryCursor exposes a Streams3 interface, as well as a `.next()` function.
4428 *
4429 * The `.cursor()` function triggers pre find hooks, but **not** post find hooks.
4430 *
4431 * ####Example
4432 *
4433 * // There are 2 ways to use a cursor. First, as a stream:
4434 * Thing.
4435 * find({ name: /^hello/ }).
4436 * cursor().
4437 * on('data', function(doc) { console.log(doc); }).
4438 * on('end', function() { console.log('Done!'); });
4439 *
4440 * // Or you can use `.next()` to manually get the next doc in the stream.
4441 * // `.next()` returns a promise, so you can use promises or callbacks.
4442 * var cursor = Thing.find({ name: /^hello/ }).cursor();
4443 * cursor.next(function(error, doc) {
4444 * console.log(doc);
4445 * });
4446 *
4447 * // Because `.next()` returns a promise, you can use co
4448 * // to easily iterate through all documents without loading them
4449 * // all into memory.
4450 * co(function*() {
4451 * const cursor = Thing.find({ name: /^hello/ }).cursor();
4452 * for (let doc = yield cursor.next(); doc != null; doc = yield cursor.next()) {
4453 * console.log(doc);
4454 * }
4455 * });
4456 *
4457 * ####Valid options
4458 *
4459 * - `transform`: optional function which accepts a mongoose document. The return value of the function will be emitted on `data` and returned by `.next()`.
4460 *
4461 * @return {QueryCursor}
4462 * @param {Object} [options]
4463 * @see QueryCursor
4464 * @api public
4465 */
4466
4467Query.prototype.cursor = function cursor(opts) {
4468 this._applyPaths();
4469 this._fields = this._castFields(this._fields);
4470 this.setOptions({ projection: this._fieldsForExec() });
4471 if (opts) {
4472 this.setOptions(opts);
4473 }
4474
4475 try {
4476 this.cast(this.model);
4477 } catch (err) {
4478 return (new QueryCursor(this, this.options))._markError(err);
4479 }
4480
4481 return new QueryCursor(this, this.options);
4482};
4483
4484// the rest of these are basically to support older Mongoose syntax with mquery
4485
4486/**
4487 * _DEPRECATED_ Alias of `maxScan`
4488 *
4489 * @deprecated
4490 * @see maxScan #query_Query-maxScan
4491 * @method maxscan
4492 * @memberOf Query
4493 * @instance
4494 */
4495
4496Query.prototype.maxscan = Query.base.maxScan;
4497
4498/**
4499 * Sets the tailable option (for use with capped collections).
4500 *
4501 * ####Example
4502 *
4503 * query.tailable() // true
4504 * query.tailable(true)
4505 * query.tailable(false)
4506 *
4507 * ####Note
4508 *
4509 * Cannot be used with `distinct()`
4510 *
4511 * @param {Boolean} bool defaults to true
4512 * @param {Object} [opts] options to set
4513 * @param {Number} [opts.numberOfRetries] if cursor is exhausted, retry this many times before giving up
4514 * @param {Number} [opts.tailableRetryInterval] if cursor is exhausted, wait this many milliseconds before retrying
4515 * @see tailable http://docs.mongodb.org/manual/tutorial/create-tailable-cursor/
4516 * @api public
4517 */
4518
4519Query.prototype.tailable = function(val, opts) {
4520 // we need to support the tailable({ awaitdata : true }) as well as the
4521 // tailable(true, {awaitdata :true}) syntax that mquery does not support
4522 if (val && val.constructor.name === 'Object') {
4523 opts = val;
4524 val = true;
4525 }
4526
4527 if (val === undefined) {
4528 val = true;
4529 }
4530
4531 if (opts && typeof opts === 'object') {
4532 for (const key in opts) {
4533 if (key === 'awaitdata') {
4534 // For backwards compatibility
4535 this.options[key] = !!opts[key];
4536 } else {
4537 this.options[key] = opts[key];
4538 }
4539 }
4540 }
4541
4542 return Query.base.tailable.call(this, val);
4543};
4544
4545/**
4546 * Declares an intersects query for `geometry()`.
4547 *
4548 * ####Example
4549 *
4550 * query.where('path').intersects().geometry({
4551 * type: 'LineString'
4552 * , coordinates: [[180.0, 11.0], [180, 9.0]]
4553 * })
4554 *
4555 * query.where('path').intersects({
4556 * type: 'LineString'
4557 * , coordinates: [[180.0, 11.0], [180, 9.0]]
4558 * })
4559 *
4560 * ####NOTE:
4561 *
4562 * **MUST** be used after `where()`.
4563 *
4564 * ####NOTE:
4565 *
4566 * In Mongoose 3.7, `intersects` changed from a getter to a function. If you need the old syntax, use [this](https://github.com/ebensing/mongoose-within).
4567 *
4568 * @method intersects
4569 * @memberOf Query
4570 * @instance
4571 * @param {Object} [arg]
4572 * @return {Query} this
4573 * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/
4574 * @see geoIntersects http://docs.mongodb.org/manual/reference/operator/geoIntersects/
4575 * @api public
4576 */
4577
4578/**
4579 * Specifies a `$geometry` condition
4580 *
4581 * ####Example
4582 *
4583 * var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]]
4584 * query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA })
4585 *
4586 * // or
4587 * var polyB = [[ 0, 0 ], [ 1, 1 ]]
4588 * query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB })
4589 *
4590 * // or
4591 * var polyC = [ 0, 0 ]
4592 * query.where('loc').within().geometry({ type: 'Point', coordinates: polyC })
4593 *
4594 * // or
4595 * query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC })
4596 *
4597 * The argument is assigned to the most recent path passed to `where()`.
4598 *
4599 * ####NOTE:
4600 *
4601 * `geometry()` **must** come after either `intersects()` or `within()`.
4602 *
4603 * The `object` argument must contain `type` and `coordinates` properties.
4604 * - type {String}
4605 * - coordinates {Array}
4606 *
4607 * @method geometry
4608 * @memberOf Query
4609 * @instance
4610 * @param {Object} object Must contain a `type` property which is a String and a `coordinates` property which is an Array. See the examples.
4611 * @return {Query} this
4612 * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/
4613 * @see http://docs.mongodb.org/manual/release-notes/2.4/#new-geospatial-indexes-with-geojson-and-improved-spherical-geometry
4614 * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
4615 * @api public
4616 */
4617
4618/**
4619 * Specifies a `$near` or `$nearSphere` condition
4620 *
4621 * These operators return documents sorted by distance.
4622 *
4623 * ####Example
4624 *
4625 * query.where('loc').near({ center: [10, 10] });
4626 * query.where('loc').near({ center: [10, 10], maxDistance: 5 });
4627 * query.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true });
4628 * query.near('loc', { center: [10, 10], maxDistance: 5 });
4629 *
4630 * @method near
4631 * @memberOf Query
4632 * @instance
4633 * @param {String} [path]
4634 * @param {Object} val
4635 * @return {Query} this
4636 * @see $near http://docs.mongodb.org/manual/reference/operator/near/
4637 * @see $nearSphere http://docs.mongodb.org/manual/reference/operator/nearSphere/
4638 * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/
4639 * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
4640 * @api public
4641 */
4642
4643/*!
4644 * Overwriting mquery is needed to support a couple different near() forms found in older
4645 * versions of mongoose
4646 * near([1,1])
4647 * near(1,1)
4648 * near(field, [1,2])
4649 * near(field, 1, 2)
4650 * In addition to all of the normal forms supported by mquery
4651 */
4652
4653Query.prototype.near = function() {
4654 const params = [];
4655 const sphere = this._mongooseOptions.nearSphere;
4656
4657 // TODO refactor
4658
4659 if (arguments.length === 1) {
4660 if (Array.isArray(arguments[0])) {
4661 params.push({center: arguments[0], spherical: sphere});
4662 } else if (typeof arguments[0] === 'string') {
4663 // just passing a path
4664 params.push(arguments[0]);
4665 } else if (utils.isObject(arguments[0])) {
4666 if (typeof arguments[0].spherical !== 'boolean') {
4667 arguments[0].spherical = sphere;
4668 }
4669 params.push(arguments[0]);
4670 } else {
4671 throw new TypeError('invalid argument');
4672 }
4673 } else if (arguments.length === 2) {
4674 if (typeof arguments[0] === 'number' && typeof arguments[1] === 'number') {
4675 params.push({center: [arguments[0], arguments[1]], spherical: sphere});
4676 } else if (typeof arguments[0] === 'string' && Array.isArray(arguments[1])) {
4677 params.push(arguments[0]);
4678 params.push({center: arguments[1], spherical: sphere});
4679 } else if (typeof arguments[0] === 'string' && utils.isObject(arguments[1])) {
4680 params.push(arguments[0]);
4681 if (typeof arguments[1].spherical !== 'boolean') {
4682 arguments[1].spherical = sphere;
4683 }
4684 params.push(arguments[1]);
4685 } else {
4686 throw new TypeError('invalid argument');
4687 }
4688 } else if (arguments.length === 3) {
4689 if (typeof arguments[0] === 'string' && typeof arguments[1] === 'number'
4690 && typeof arguments[2] === 'number') {
4691 params.push(arguments[0]);
4692 params.push({center: [arguments[1], arguments[2]], spherical: sphere});
4693 } else {
4694 throw new TypeError('invalid argument');
4695 }
4696 } else {
4697 throw new TypeError('invalid argument');
4698 }
4699
4700 return Query.base.near.apply(this, params);
4701};
4702
4703/**
4704 * _DEPRECATED_ Specifies a `$nearSphere` condition
4705 *
4706 * ####Example
4707 *
4708 * query.where('loc').nearSphere({ center: [10, 10], maxDistance: 5 });
4709 *
4710 * **Deprecated.** Use `query.near()` instead with the `spherical` option set to `true`.
4711 *
4712 * ####Example
4713 *
4714 * query.where('loc').near({ center: [10, 10], spherical: true });
4715 *
4716 * @deprecated
4717 * @see near() #query_Query-near
4718 * @see $near http://docs.mongodb.org/manual/reference/operator/near/
4719 * @see $nearSphere http://docs.mongodb.org/manual/reference/operator/nearSphere/
4720 * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/
4721 */
4722
4723Query.prototype.nearSphere = function() {
4724 this._mongooseOptions.nearSphere = true;
4725 this.near.apply(this, arguments);
4726 return this;
4727};
4728
4729/**
4730 * Returns an asyncIterator for use with [`for/await/of` loops](http://bit.ly/async-iterators)
4731 * This function *only* works for `find()` queries.
4732 * You do not need to call this function explicitly, the JavaScript runtime
4733 * will call it for you.
4734 *
4735 * ####Example
4736 *
4737 * for await (const doc of Model.aggregate([{ $sort: { name: 1 } }])) {
4738 * console.log(doc.name);
4739 * }
4740 *
4741 * Node.js 10.x supports async iterators natively without any flags. You can
4742 * enable async iterators in Node.js 8.x using the [`--harmony_async_iteration` flag](https://github.com/tc39/proposal-async-iteration/issues/117#issuecomment-346695187).
4743 *
4744 * **Note:** This function is not if `Symbol.asyncIterator` is undefined. If
4745 * `Symbol.asyncIterator` is undefined, that means your Node.js version does not
4746 * support async iterators.
4747 *
4748 * @method Symbol.asyncIterator
4749 * @memberOf Query
4750 * @instance
4751 * @api public
4752 */
4753
4754if (Symbol.asyncIterator != null) {
4755 Query.prototype[Symbol.asyncIterator] = function() {
4756 return this.cursor().transformNull().map(doc => {
4757 return doc == null ? { done: true } : { value: doc, done: false };
4758 });
4759 };
4760}
4761
4762/**
4763 * Specifies a $polygon condition
4764 *
4765 * ####Example
4766 *
4767 * query.where('loc').within().polygon([10,20], [13, 25], [7,15])
4768 * query.polygon('loc', [10,20], [13, 25], [7,15])
4769 *
4770 * @method polygon
4771 * @memberOf Query
4772 * @instance
4773 * @param {String|Array} [path]
4774 * @param {Array|Object} [coordinatePairs...]
4775 * @return {Query} this
4776 * @see $polygon http://docs.mongodb.org/manual/reference/operator/polygon/
4777 * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
4778 * @api public
4779 */
4780
4781/**
4782 * Specifies a $box condition
4783 *
4784 * ####Example
4785 *
4786 * var lowerLeft = [40.73083, -73.99756]
4787 * var upperRight= [40.741404, -73.988135]
4788 *
4789 * query.where('loc').within().box(lowerLeft, upperRight)
4790 * query.box({ ll : lowerLeft, ur : upperRight })
4791 *
4792 * @method box
4793 * @memberOf Query
4794 * @instance
4795 * @see $box http://docs.mongodb.org/manual/reference/operator/box/
4796 * @see within() Query#within #query_Query-within
4797 * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
4798 * @param {Object} val
4799 * @param [Array] Upper Right Coords
4800 * @return {Query} this
4801 * @api public
4802 */
4803
4804/*!
4805 * this is needed to support the mongoose syntax of:
4806 * box(field, { ll : [x,y], ur : [x2,y2] })
4807 * box({ ll : [x,y], ur : [x2,y2] })
4808 */
4809
4810Query.prototype.box = function(ll, ur) {
4811 if (!Array.isArray(ll) && utils.isObject(ll)) {
4812 ur = ll.ur;
4813 ll = ll.ll;
4814 }
4815 return Query.base.box.call(this, ll, ur);
4816};
4817
4818/**
4819 * Specifies a $center or $centerSphere condition.
4820 *
4821 * ####Example
4822 *
4823 * var area = { center: [50, 50], radius: 10, unique: true }
4824 * query.where('loc').within().circle(area)
4825 * // alternatively
4826 * query.circle('loc', area);
4827 *
4828 * // spherical calculations
4829 * var area = { center: [50, 50], radius: 10, unique: true, spherical: true }
4830 * query.where('loc').within().circle(area)
4831 * // alternatively
4832 * query.circle('loc', area);
4833 *
4834 * New in 3.7.0
4835 *
4836 * @method circle
4837 * @memberOf Query
4838 * @instance
4839 * @param {String} [path]
4840 * @param {Object} area
4841 * @return {Query} this
4842 * @see $center http://docs.mongodb.org/manual/reference/operator/center/
4843 * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/
4844 * @see $geoWithin http://docs.mongodb.org/manual/reference/operator/geoWithin/
4845 * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
4846 * @api public
4847 */
4848
4849/**
4850 * _DEPRECATED_ Alias for [circle](#query_Query-circle)
4851 *
4852 * **Deprecated.** Use [circle](#query_Query-circle) instead.
4853 *
4854 * @deprecated
4855 * @method center
4856 * @memberOf Query
4857 * @instance
4858 * @api public
4859 */
4860
4861Query.prototype.center = Query.base.circle;
4862
4863/**
4864 * _DEPRECATED_ Specifies a $centerSphere condition
4865 *
4866 * **Deprecated.** Use [circle](#query_Query-circle) instead.
4867 *
4868 * ####Example
4869 *
4870 * var area = { center: [50, 50], radius: 10 };
4871 * query.where('loc').within().centerSphere(area);
4872 *
4873 * @deprecated
4874 * @param {String} [path]
4875 * @param {Object} val
4876 * @return {Query} this
4877 * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
4878 * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/
4879 * @api public
4880 */
4881
4882Query.prototype.centerSphere = function() {
4883 if (arguments[0] && arguments[0].constructor.name === 'Object') {
4884 arguments[0].spherical = true;
4885 }
4886
4887 if (arguments[1] && arguments[1].constructor.name === 'Object') {
4888 arguments[1].spherical = true;
4889 }
4890
4891 Query.base.circle.apply(this, arguments);
4892};
4893
4894/**
4895 * Determines if field selection has been made.
4896 *
4897 * @method selected
4898 * @memberOf Query
4899 * @instance
4900 * @return {Boolean}
4901 * @api public
4902 */
4903
4904/**
4905 * Determines if inclusive field selection has been made.
4906 *
4907 * query.selectedInclusively() // false
4908 * query.select('name')
4909 * query.selectedInclusively() // true
4910 *
4911 * @method selectedInclusively
4912 * @memberOf Query
4913 * @instance
4914 * @return {Boolean}
4915 * @api public
4916 */
4917
4918Query.prototype.selectedInclusively = function selectedInclusively() {
4919 return isInclusive(this._fields);
4920};
4921
4922/**
4923 * Determines if exclusive field selection has been made.
4924 *
4925 * query.selectedExclusively() // false
4926 * query.select('-name')
4927 * query.selectedExclusively() // true
4928 * query.selectedInclusively() // false
4929 *
4930 * @method selectedExclusively
4931 * @memberOf Query
4932 * @instance
4933 * @return {Boolean}
4934 * @api public
4935 */
4936
4937Query.prototype.selectedExclusively = function selectedExclusively() {
4938 if (!this._fields) {
4939 return false;
4940 }
4941
4942 const keys = Object.keys(this._fields);
4943 if (keys.length === 0) {
4944 return false;
4945 }
4946
4947 for (let i = 0; i < keys.length; ++i) {
4948 const key = keys[i];
4949 if (key === '_id') {
4950 continue;
4951 }
4952 if (this._fields[key] === 0 || this._fields[key] === false) {
4953 return true;
4954 }
4955 }
4956
4957 return false;
4958};
4959
4960/*!
4961 * Export
4962 */
4963
4964module.exports = Query;