UNPKG

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