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