arnaucube
arnaucube/thoughtsPublic Self-hosted repository
thoughts/node_modules/mongoose/lib/query.js
node_modules/mongoose/lib/query.jsRaw
   1/*!
   2 * Module dependencies.
   3 */
   4
   5var PromiseProvider = require('./promise_provider');
   6var QueryCursor = require('./querycursor');
   7var QueryStream = require('./querystream');
   8var StrictModeError = require('./error/strict');
   9var cast = require('./cast');
  10var helpers = require('./queryhelpers');
  11var mquery = require('mquery');
  12var readPref = require('./drivers').ReadPreference;
  13var setDefaultsOnInsert = require('./services/setDefaultsOnInsert');
  14var updateValidators = require('./services/updateValidators');
  15var util = require('util');
  16var utils = require('./utils');
  17
  18/**
  19 * Query constructor used for building queries.
  20 *
  21 * ####Example:
  22 *
  23 *     var query = new Query();
  24 *     query.setOptions({ lean : true });
  25 *     query.collection(model.collection);
  26 *     query.where('age').gte(21).exec(callback);
  27 *
  28 * @param {Object} [options]
  29 * @param {Object} [model]
  30 * @param {Object} [conditions]
  31 * @param {Object} [collection] Mongoose collection
  32 * @api private
  33 */
  34
  35function Query(conditions, options, model, collection) {
  36  // this stuff is for dealing with custom queries created by #toConstructor
  37  if (!this._mongooseOptions) {
  38    this._mongooseOptions = {};
  39  }
  40
  41  // this is the case where we have a CustomQuery, we need to check if we got
  42  // options passed in, and if we did, merge them in
  43  if (options) {
  44    var keys = Object.keys(options);
  45    for (var i = 0; i < keys.length; ++i) {
  46      var k = keys[i];
  47      this._mongooseOptions[k] = options[k];
  48    }
  49  }
  50
  51  if (collection) {
  52    this.mongooseCollection = collection;
  53  }
  54
  55  if (model) {
  56    this.model = model;
  57    this.schema = model.schema;
  58  }
  59
  60  // this is needed because map reduce returns a model that can be queried, but
  61  // all of the queries on said model should be lean
  62  if (this.model && this.model._mapreduce) {
  63    this.lean();
  64  }
  65
  66  // inherit mquery
  67  mquery.call(this, this.mongooseCollection, options);
  68
  69  if (conditions) {
  70    this.find(conditions);
  71  }
  72
  73  if (this.schema) {
  74    var kareemOptions = { useErrorHandlers: true };
  75    this._count = this.model.hooks.createWrapper('count',
  76        Query.prototype._count, this, kareemOptions);
  77    this._execUpdate = this.model.hooks.createWrapper('update',
  78        Query.prototype._execUpdate, this, kareemOptions);
  79    this._find = this.model.hooks.createWrapper('find',
  80        Query.prototype._find, this, kareemOptions);
  81    this._findOne = this.model.hooks.createWrapper('findOne',
  82        Query.prototype._findOne, this, kareemOptions);
  83    this._findOneAndRemove = this.model.hooks.createWrapper('findOneAndRemove',
  84        Query.prototype._findOneAndRemove, this, kareemOptions);
  85    this._findOneAndUpdate = this.model.hooks.createWrapper('findOneAndUpdate',
  86        Query.prototype._findOneAndUpdate, this, kareemOptions);
  87  }
  88}
  89
  90/*!
  91 * inherit mquery
  92 */
  93
  94Query.prototype = new mquery;
  95Query.prototype.constructor = Query;
  96Query.base = mquery.prototype;
  97
  98/**
  99 * Flag to opt out of using `$geoWithin`.
 100 *
 101 *     mongoose.Query.use$geoWithin = false;
 102 *
 103 * 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.
 104 *
 105 * @see http://docs.mongodb.org/manual/reference/operator/geoWithin/
 106 * @default true
 107 * @property use$geoWithin
 108 * @memberOf Query
 109 * @receiver Query
 110 * @api public
 111 */
 112
 113Query.use$geoWithin = mquery.use$geoWithin;
 114
 115/**
 116 * Converts this query to a customized, reusable query constructor with all arguments and options retained.
 117 *
 118 * ####Example
 119 *
 120 *     // Create a query for adventure movies and read from the primary
 121 *     // node in the replica-set unless it is down, in which case we'll
 122 *     // read from a secondary node.
 123 *     var query = Movie.find({ tags: 'adventure' }).read('primaryPreferred');
 124 *
 125 *     // create a custom Query constructor based off these settings
 126 *     var Adventure = query.toConstructor();
 127 *
 128 *     // Adventure is now a subclass of mongoose.Query and works the same way but with the
 129 *     // default query parameters and options set.
 130 *     Adventure().exec(callback)
 131 *
 132 *     // further narrow down our query results while still using the previous settings
 133 *     Adventure().where({ name: /^Life/ }).exec(callback);
 134 *
 135 *     // since Adventure is a stand-alone constructor we can also add our own
 136 *     // helper methods and getters without impacting global queries
 137 *     Adventure.prototype.startsWith = function (prefix) {
 138 *       this.where({ name: new RegExp('^' + prefix) })
 139 *       return this;
 140 *     }
 141 *     Object.defineProperty(Adventure.prototype, 'highlyRated', {
 142 *       get: function () {
 143 *         this.where({ rating: { $gt: 4.5 }});
 144 *         return this;
 145 *       }
 146 *     })
 147 *     Adventure().highlyRated.startsWith('Life').exec(callback)
 148 *
 149 * New in 3.7.3
 150 *
 151 * @return {Query} subclass-of-Query
 152 * @api public
 153 */
 154
 155Query.prototype.toConstructor = function toConstructor() {
 156  var model = this.model;
 157  var coll = this.mongooseCollection;
 158
 159  var CustomQuery = function(criteria, options) {
 160    if (!(this instanceof CustomQuery)) {
 161      return new CustomQuery(criteria, options);
 162    }
 163    this._mongooseOptions = utils.clone(p._mongooseOptions);
 164    Query.call(this, criteria, options || null, model, coll);
 165  };
 166
 167  util.inherits(CustomQuery, Query);
 168
 169  // set inherited defaults
 170  var p = CustomQuery.prototype;
 171
 172  p.options = {};
 173
 174  p.setOptions(this.options);
 175
 176  p.op = this.op;
 177  p._conditions = utils.clone(this._conditions);
 178  p._fields = utils.clone(this._fields);
 179  p._update = utils.clone(this._update);
 180  p._path = this._path;
 181  p._distinct = this._distinct;
 182  p._collection = this._collection;
 183  p._mongooseOptions = this._mongooseOptions;
 184
 185  return CustomQuery;
 186};
 187
 188/**
 189 * Specifies a javascript function or expression to pass to MongoDBs query system.
 190 *
 191 * ####Example
 192 *
 193 *     query.$where('this.comments.length === 10 || this.name.length === 5')
 194 *
 195 *     // or
 196 *
 197 *     query.$where(function () {
 198 *       return this.comments.length === 10 || this.name.length === 5;
 199 *     })
 200 *
 201 * ####NOTE:
 202 *
 203 * Only use `$where` when you have a condition that cannot be met using other MongoDB operators like `$lt`.
 204 * **Be sure to read about all of [its caveats](http://docs.mongodb.org/manual/reference/operator/where/) before using.**
 205 *
 206 * @see $where http://docs.mongodb.org/manual/reference/operator/where/
 207 * @method $where
 208 * @param {String|Function} js javascript string or function
 209 * @return {Query} this
 210 * @memberOf Query
 211 * @method $where
 212 * @api public
 213 */
 214
 215/**
 216 * Specifies a `path` for use with chaining.
 217 *
 218 * ####Example
 219 *
 220 *     // instead of writing:
 221 *     User.find({age: {$gte: 21, $lte: 65}}, callback);
 222 *
 223 *     // we can instead write:
 224 *     User.where('age').gte(21).lte(65);
 225 *
 226 *     // passing query conditions is permitted
 227 *     User.find().where({ name: 'vonderful' })
 228 *
 229 *     // chaining
 230 *     User
 231 *     .where('age').gte(21).lte(65)
 232 *     .where('name', /^vonderful/i)
 233 *     .where('friends').slice(10)
 234 *     .exec(callback)
 235 *
 236 * @method where
 237 * @memberOf Query
 238 * @param {String|Object} [path]
 239 * @param {any} [val]
 240 * @return {Query} this
 241 * @api public
 242 */
 243
 244/**
 245 * Specifies the complementary comparison value for paths specified with `where()`
 246 *
 247 * ####Example
 248 *
 249 *     User.where('age').equals(49);
 250 *
 251 *     // is the same as
 252 *
 253 *     User.where('age', 49);
 254 *
 255 * @method equals
 256 * @memberOf Query
 257 * @param {Object} val
 258 * @return {Query} this
 259 * @api public
 260 */
 261
 262/**
 263 * Specifies arguments for an `$or` condition.
 264 *
 265 * ####Example
 266 *
 267 *     query.or([{ color: 'red' }, { status: 'emergency' }])
 268 *
 269 * @see $or http://docs.mongodb.org/manual/reference/operator/or/
 270 * @method or
 271 * @memberOf Query
 272 * @param {Array} array array of conditions
 273 * @return {Query} this
 274 * @api public
 275 */
 276
 277/**
 278 * Specifies arguments for a `$nor` condition.
 279 *
 280 * ####Example
 281 *
 282 *     query.nor([{ color: 'green' }, { status: 'ok' }])
 283 *
 284 * @see $nor http://docs.mongodb.org/manual/reference/operator/nor/
 285 * @method nor
 286 * @memberOf Query
 287 * @param {Array} array array of conditions
 288 * @return {Query} this
 289 * @api public
 290 */
 291
 292/**
 293 * Specifies arguments for a `$and` condition.
 294 *
 295 * ####Example
 296 *
 297 *     query.and([{ color: 'green' }, { status: 'ok' }])
 298 *
 299 * @method and
 300 * @memberOf Query
 301 * @see $and http://docs.mongodb.org/manual/reference/operator/and/
 302 * @param {Array} array array of conditions
 303 * @return {Query} this
 304 * @api public
 305 */
 306
 307/**
 308 * Specifies a $gt query condition.
 309 *
 310 * When called with one argument, the most recent path passed to `where()` is used.
 311 *
 312 * ####Example
 313 *
 314 *     Thing.find().where('age').gt(21)
 315 *
 316 *     // or
 317 *     Thing.find().gt('age', 21)
 318 *
 319 * @method gt
 320 * @memberOf Query
 321 * @param {String} [path]
 322 * @param {Number} val
 323 * @see $gt http://docs.mongodb.org/manual/reference/operator/gt/
 324 * @api public
 325 */
 326
 327/**
 328 * Specifies a $gte query condition.
 329 *
 330 * When called with one argument, the most recent path passed to `where()` is used.
 331 *
 332 * @method gte
 333 * @memberOf Query
 334 * @param {String} [path]
 335 * @param {Number} val
 336 * @see $gte http://docs.mongodb.org/manual/reference/operator/gte/
 337 * @api public
 338 */
 339
 340/**
 341 * Specifies a $lt query condition.
 342 *
 343 * When called with one argument, the most recent path passed to `where()` is used.
 344 *
 345 * @method lt
 346 * @memberOf Query
 347 * @param {String} [path]
 348 * @param {Number} val
 349 * @see $lt http://docs.mongodb.org/manual/reference/operator/lt/
 350 * @api public
 351 */
 352
 353/**
 354 * Specifies a $lte query condition.
 355 *
 356 * When called with one argument, the most recent path passed to `where()` is used.
 357 *
 358 * @method lte
 359 * @see $lte http://docs.mongodb.org/manual/reference/operator/lte/
 360 * @memberOf Query
 361 * @param {String} [path]
 362 * @param {Number} val
 363 * @api public
 364 */
 365
 366/**
 367 * Specifies a $ne query condition.
 368 *
 369 * When called with one argument, the most recent path passed to `where()` is used.
 370 *
 371 * @see $ne http://docs.mongodb.org/manual/reference/operator/ne/
 372 * @method ne
 373 * @memberOf Query
 374 * @param {String} [path]
 375 * @param {Number} val
 376 * @api public
 377 */
 378
 379/**
 380 * Specifies an $in query condition.
 381 *
 382 * When called with one argument, the most recent path passed to `where()` is used.
 383 *
 384 * @see $in http://docs.mongodb.org/manual/reference/operator/in/
 385 * @method in
 386 * @memberOf Query
 387 * @param {String} [path]
 388 * @param {Number} val
 389 * @api public
 390 */
 391
 392/**
 393 * Specifies an $nin query condition.
 394 *
 395 * When called with one argument, the most recent path passed to `where()` is used.
 396 *
 397 * @see $nin http://docs.mongodb.org/manual/reference/operator/nin/
 398 * @method nin
 399 * @memberOf Query
 400 * @param {String} [path]
 401 * @param {Number} val
 402 * @api public
 403 */
 404
 405/**
 406 * Specifies an $all query condition.
 407 *
 408 * When called with one argument, the most recent path passed to `where()` is used.
 409 *
 410 * @see $all http://docs.mongodb.org/manual/reference/operator/all/
 411 * @method all
 412 * @memberOf Query
 413 * @param {String} [path]
 414 * @param {Number} val
 415 * @api public
 416 */
 417
 418/**
 419 * Specifies a $size query condition.
 420 *
 421 * When called with one argument, the most recent path passed to `where()` is used.
 422 *
 423 * ####Example
 424 *
 425 *     MyModel.where('tags').size(0).exec(function (err, docs) {
 426 *       if (err) return handleError(err);
 427 *
 428 *       assert(Array.isArray(docs));
 429 *       console.log('documents with 0 tags', docs);
 430 *     })
 431 *
 432 * @see $size http://docs.mongodb.org/manual/reference/operator/size/
 433 * @method size
 434 * @memberOf Query
 435 * @param {String} [path]
 436 * @param {Number} val
 437 * @api public
 438 */
 439
 440/**
 441 * Specifies a $regex query condition.
 442 *
 443 * When called with one argument, the most recent path passed to `where()` is used.
 444 *
 445 * @see $regex http://docs.mongodb.org/manual/reference/operator/regex/
 446 * @method regex
 447 * @memberOf Query
 448 * @param {String} [path]
 449 * @param {Number} val
 450 * @api public
 451 */
 452
 453/**
 454 * Specifies a $maxDistance query condition.
 455 *
 456 * When called with one argument, the most recent path passed to `where()` is used.
 457 *
 458 * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/
 459 * @method maxDistance
 460 * @memberOf Query
 461 * @param {String} [path]
 462 * @param {Number} val
 463 * @api public
 464 */
 465
 466/**
 467 * Specifies a `$mod` condition
 468 *
 469 * @method mod
 470 * @memberOf Query
 471 * @param {String} [path]
 472 * @param {Number} val
 473 * @return {Query} this
 474 * @see $mod http://docs.mongodb.org/manual/reference/operator/mod/
 475 * @api public
 476 */
 477
 478/**
 479 * Specifies an `$exists` condition
 480 *
 481 * ####Example
 482 *
 483 *     // { name: { $exists: true }}
 484 *     Thing.where('name').exists()
 485 *     Thing.where('name').exists(true)
 486 *     Thing.find().exists('name')
 487 *
 488 *     // { name: { $exists: false }}
 489 *     Thing.where('name').exists(false);
 490 *     Thing.find().exists('name', false);
 491 *
 492 * @method exists
 493 * @memberOf Query
 494 * @param {String} [path]
 495 * @param {Number} val
 496 * @return {Query} this
 497 * @see $exists http://docs.mongodb.org/manual/reference/operator/exists/
 498 * @api public
 499 */
 500
 501/**
 502 * Specifies an `$elemMatch` condition
 503 *
 504 * ####Example
 505 *
 506 *     query.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}})
 507 *
 508 *     query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}})
 509 *
 510 *     query.elemMatch('comment', function (elem) {
 511 *       elem.where('author').equals('autobot');
 512 *       elem.where('votes').gte(5);
 513 *     })
 514 *
 515 *     query.where('comment').elemMatch(function (elem) {
 516 *       elem.where({ author: 'autobot' });
 517 *       elem.where('votes').gte(5);
 518 *     })
 519 *
 520 * @method elemMatch
 521 * @memberOf Query
 522 * @param {String|Object|Function} path
 523 * @param {Object|Function} criteria
 524 * @return {Query} this
 525 * @see $elemMatch http://docs.mongodb.org/manual/reference/operator/elemMatch/
 526 * @api public
 527 */
 528
 529/**
 530 * Defines a `$within` or `$geoWithin` argument for geo-spatial queries.
 531 *
 532 * ####Example
 533 *
 534 *     query.where(path).within().box()
 535 *     query.where(path).within().circle()
 536 *     query.where(path).within().geometry()
 537 *
 538 *     query.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true });
 539 *     query.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] });
 540 *     query.where('loc').within({ polygon: [[],[],[],[]] });
 541 *
 542 *     query.where('loc').within([], [], []) // polygon
 543 *     query.where('loc').within([], []) // box
 544 *     query.where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry
 545 *
 546 * **MUST** be used after `where()`.
 547 *
 548 * ####NOTE:
 549 *
 550 * As of Mongoose 3.7, `$geoWithin` is always used for queries. To change this behavior, see [Query.use$geoWithin](#query_Query-use%2524geoWithin).
 551 *
 552 * ####NOTE:
 553 *
 554 * 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).
 555 *
 556 * @method within
 557 * @see $polygon http://docs.mongodb.org/manual/reference/operator/polygon/
 558 * @see $box http://docs.mongodb.org/manual/reference/operator/box/
 559 * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/
 560 * @see $center http://docs.mongodb.org/manual/reference/operator/center/
 561 * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/
 562 * @memberOf Query
 563 * @return {Query} this
 564 * @api public
 565 */
 566
 567/**
 568 * Specifies a $slice projection for an array.
 569 *
 570 * ####Example
 571 *
 572 *     query.slice('comments', 5)
 573 *     query.slice('comments', -5)
 574 *     query.slice('comments', [10, 5])
 575 *     query.where('comments').slice(5)
 576 *     query.where('comments').slice([-10, 5])
 577 *
 578 * @method slice
 579 * @memberOf Query
 580 * @param {String} [path]
 581 * @param {Number} val number/range of elements to slice
 582 * @return {Query} this
 583 * @see mongodb http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields#RetrievingaSubsetofFields-RetrievingaSubrangeofArrayElements
 584 * @see $slice http://docs.mongodb.org/manual/reference/projection/slice/#prj._S_slice
 585 * @api public
 586 */
 587
 588/**
 589 * Specifies the maximum number of documents the query will return.
 590 *
 591 * ####Example
 592 *
 593 *     query.limit(20)
 594 *
 595 * ####Note
 596 *
 597 * Cannot be used with `distinct()`
 598 *
 599 * @method limit
 600 * @memberOf Query
 601 * @param {Number} val
 602 * @api public
 603 */
 604
 605/**
 606 * Specifies the number of documents to skip.
 607 *
 608 * ####Example
 609 *
 610 *     query.skip(100).limit(20)
 611 *
 612 * ####Note
 613 *
 614 * Cannot be used with `distinct()`
 615 *
 616 * @method skip
 617 * @memberOf Query
 618 * @param {Number} val
 619 * @see cursor.skip http://docs.mongodb.org/manual/reference/method/cursor.skip/
 620 * @api public
 621 */
 622
 623/**
 624 * Specifies the maxScan option.
 625 *
 626 * ####Example
 627 *
 628 *     query.maxScan(100)
 629 *
 630 * ####Note
 631 *
 632 * Cannot be used with `distinct()`
 633 *
 634 * @method maxScan
 635 * @memberOf Query
 636 * @param {Number} val
 637 * @see maxScan http://docs.mongodb.org/manual/reference/operator/maxScan/
 638 * @api public
 639 */
 640
 641/**
 642 * Specifies the batchSize option.
 643 *
 644 * ####Example
 645 *
 646 *     query.batchSize(100)
 647 *
 648 * ####Note
 649 *
 650 * Cannot be used with `distinct()`
 651 *
 652 * @method batchSize
 653 * @memberOf Query
 654 * @param {Number} val
 655 * @see batchSize http://docs.mongodb.org/manual/reference/method/cursor.batchSize/
 656 * @api public
 657 */
 658
 659/**
 660 * Specifies the `comment` option.
 661 *
 662 * ####Example
 663 *
 664 *     query.comment('login query')
 665 *
 666 * ####Note
 667 *
 668 * Cannot be used with `distinct()`
 669 *
 670 * @method comment
 671 * @memberOf Query
 672 * @param {Number} val
 673 * @see comment http://docs.mongodb.org/manual/reference/operator/comment/
 674 * @api public
 675 */
 676
 677/**
 678 * Specifies this query as a `snapshot` query.
 679 *
 680 * ####Example
 681 *
 682 *     query.snapshot() // true
 683 *     query.snapshot(true)
 684 *     query.snapshot(false)
 685 *
 686 * ####Note
 687 *
 688 * Cannot be used with `distinct()`
 689 *
 690 * @method snapshot
 691 * @memberOf Query
 692 * @see snapshot http://docs.mongodb.org/manual/reference/operator/snapshot/
 693 * @return {Query} this
 694 * @api public
 695 */
 696
 697/**
 698 * Sets query hints.
 699 *
 700 * ####Example
 701 *
 702 *     query.hint({ indexA: 1, indexB: -1})
 703 *
 704 * ####Note
 705 *
 706 * Cannot be used with `distinct()`
 707 *
 708 * @method hint
 709 * @memberOf Query
 710 * @param {Object} val a hint object
 711 * @return {Query} this
 712 * @see $hint http://docs.mongodb.org/manual/reference/operator/hint/
 713 * @api public
 714 */
 715
 716/**
 717 * Specifies which document fields to include or exclude (also known as the query "projection")
 718 *
 719 * 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).
 720 *
 721 * ####Example
 722 *
 723 *     // include a and b, exclude other fields
 724 *     query.select('a b');
 725 *
 726 *     // exclude c and d, include other fields
 727 *     query.select('-c -d');
 728 *
 729 *     // or you may use object notation, useful when
 730 *     // you have keys already prefixed with a "-"
 731 *     query.select({ a: 1, b: 1 });
 732 *     query.select({ c: 0, d: 0 });
 733 *
 734 *     // force inclusion of field excluded at schema level
 735 *     query.select('+path')
 736 *
 737 * ####NOTE:
 738 *
 739 * Cannot be used with `distinct()`.
 740 *
 741 * _v2 had slightly different syntax such as allowing arrays of field names. This support was removed in v3._
 742 *
 743 * @method select
 744 * @memberOf Query
 745 * @param {Object|String} arg
 746 * @return {Query} this
 747 * @see SchemaType
 748 * @api public
 749 */
 750
 751/**
 752 * _DEPRECATED_ Sets the slaveOk option.
 753 *
 754 * **Deprecated** in MongoDB 2.2 in favor of [read preferences](#query_Query-read).
 755 *
 756 * ####Example:
 757 *
 758 *     query.slaveOk() // true
 759 *     query.slaveOk(true)
 760 *     query.slaveOk(false)
 761 *
 762 * @method slaveOk
 763 * @memberOf Query
 764 * @deprecated use read() preferences instead if on mongodb >= 2.2
 765 * @param {Boolean} v defaults to true
 766 * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference
 767 * @see slaveOk http://docs.mongodb.org/manual/reference/method/rs.slaveOk/
 768 * @see read() #query_Query-read
 769 * @return {Query} this
 770 * @api public
 771 */
 772
 773/**
 774 * Determines the MongoDB nodes from which to read.
 775 *
 776 * ####Preferences:
 777 *
 778 *     primary - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags.
 779 *     secondary            Read from secondary if available, otherwise error.
 780 *     primaryPreferred     Read from primary if available, otherwise a secondary.
 781 *     secondaryPreferred   Read from a secondary if available, otherwise read from the primary.
 782 *     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.
 783 *
 784 * Aliases
 785 *
 786 *     p   primary
 787 *     pp  primaryPreferred
 788 *     s   secondary
 789 *     sp  secondaryPreferred
 790 *     n   nearest
 791 *
 792 * ####Example:
 793 *
 794 *     new Query().read('primary')
 795 *     new Query().read('p')  // same as primary
 796 *
 797 *     new Query().read('primaryPreferred')
 798 *     new Query().read('pp') // same as primaryPreferred
 799 *
 800 *     new Query().read('secondary')
 801 *     new Query().read('s')  // same as secondary
 802 *
 803 *     new Query().read('secondaryPreferred')
 804 *     new Query().read('sp') // same as secondaryPreferred
 805 *
 806 *     new Query().read('nearest')
 807 *     new Query().read('n')  // same as nearest
 808 *
 809 *     // read from secondaries with matching tags
 810 *     new Query().read('s', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }])
 811 *
 812 * 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).
 813 *
 814 * @method read
 815 * @memberOf Query
 816 * @param {String} pref one of the listed preference options or aliases
 817 * @param {Array} [tags] optional tags for this query
 818 * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference
 819 * @see driver http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences
 820 * @return {Query} this
 821 * @api public
 822 */
 823
 824Query.prototype.read = function read(pref, tags) {
 825  // first cast into a ReadPreference object to support tags
 826  var read = readPref.call(readPref, pref, tags);
 827  return Query.base.read.call(this, read);
 828};
 829
 830/**
 831 * Merges another Query or conditions object into this one.
 832 *
 833 * When a Query is passed, conditions, field selection and options are merged.
 834 *
 835 * New in 3.7.0
 836 *
 837 * @method merge
 838 * @memberOf Query
 839 * @param {Query|Object} source
 840 * @return {Query} this
 841 */
 842
 843/**
 844 * Sets query options.
 845 *
 846 * ####Options:
 847 *
 848 * - [tailable](http://www.mongodb.org/display/DOCS/Tailable+Cursors) *
 849 * - [sort](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsort(\)%7D%7D) *
 850 * - [limit](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D) *
 851 * - [skip](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D) *
 852 * - [maxscan](https://docs.mongodb.org/v3.2/reference/operator/meta/maxScan/#metaOp._S_maxScan) *
 853 * - [batchSize](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D) *
 854 * - [comment](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment) *
 855 * - [snapshot](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D) *
 856 * - [hint](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint) *
 857 * - [readPreference](http://docs.mongodb.org/manual/applications/replication/#read-preference) **
 858 * - [lean](./api.html#query_Query-lean) *
 859 * - [safe](http://www.mongodb.org/display/DOCS/getLastError+Command)
 860 *
 861 * _* denotes a query helper method is also available_
 862 * _** query helper method to set `readPreference` is `read()`_
 863 *
 864 * @param {Object} options
 865 * @api public
 866 */
 867
 868Query.prototype.setOptions = function(options, overwrite) {
 869  // overwrite is only for internal use
 870  if (overwrite) {
 871    // ensure that _mongooseOptions & options are two different objects
 872    this._mongooseOptions = (options && utils.clone(options)) || {};
 873    this.options = options || {};
 874
 875    if ('populate' in options) {
 876      this.populate(this._mongooseOptions);
 877    }
 878    return this;
 879  }
 880
 881  if (!(options && options.constructor.name === 'Object')) {
 882    return this;
 883  }
 884
 885  return Query.base.setOptions.call(this, options);
 886};
 887
 888/**
 889 * Returns the current query conditions as a JSON object.
 890 *
 891 * ####Example:
 892 *
 893 *     var query = new Query();
 894 *     query.find({ a: 1 }).where('b').gt(2);
 895 *     query.getQuery(); // { a: 1, b: { $gt: 2 } }
 896 *
 897 * @return {Object} current query conditions
 898 * @api public
 899 */
 900
 901Query.prototype.getQuery = function() {
 902  return this._conditions;
 903};
 904
 905/**
 906 * Returns the current update operations as a JSON object.
 907 *
 908 * ####Example:
 909 *
 910 *     var query = new Query();
 911 *     query.update({}, { $set: { a: 5 } });
 912 *     query.getUpdate(); // { $set: { a: 5 } }
 913 *
 914 * @return {Object} current update operations
 915 * @api public
 916 */
 917
 918Query.prototype.getUpdate = function() {
 919  return this._update;
 920};
 921
 922/**
 923 * Returns fields selection for this query.
 924 *
 925 * @method _fieldsForExec
 926 * @return {Object}
 927 * @api private
 928 * @receiver Query
 929 */
 930
 931/**
 932 * Return an update document with corrected $set operations.
 933 *
 934 * @method _updateForExec
 935 * @api private
 936 * @receiver Query
 937 */
 938
 939Query.prototype._updateForExec = function() {
 940  var update = utils.clone(this._update, { retainKeyOrder: true });
 941  var ops = Object.keys(update);
 942  var i = ops.length;
 943  var ret = {};
 944
 945  while (i--) {
 946    var op = ops[i];
 947
 948    if (this.options.overwrite) {
 949      ret[op] = update[op];
 950      continue;
 951    }
 952
 953    if ('$' !== op[0]) {
 954      // fix up $set sugar
 955      if (!ret.$set) {
 956        if (update.$set) {
 957          ret.$set = update.$set;
 958        } else {
 959          ret.$set = {};
 960        }
 961      }
 962      ret.$set[op] = update[op];
 963      ops.splice(i, 1);
 964      if (!~ops.indexOf('$set')) ops.push('$set');
 965    } else if ('$set' === op) {
 966      if (!ret.$set) {
 967        ret[op] = update[op];
 968      }
 969    } else {
 970      ret[op] = update[op];
 971    }
 972  }
 973
 974  this._compiledUpdate = ret;
 975  return ret;
 976};
 977
 978/**
 979 * Makes sure _path is set.
 980 *
 981 * @method _ensurePath
 982 * @param {String} method
 983 * @api private
 984 * @receiver Query
 985 */
 986
 987/**
 988 * Determines if `conds` can be merged using `mquery().merge()`
 989 *
 990 * @method canMerge
 991 * @memberOf Query
 992 * @param {Object} conds
 993 * @return {Boolean}
 994 * @api private
 995 */
 996
 997/**
 998 * Returns default options for this query.
 999 *
1000 * @param {Model} model
1001 * @api private
1002 */
1003
1004Query.prototype._optionsForExec = function(model) {
1005  var options = Query.base._optionsForExec.call(this);
1006
1007  delete options.populate;
1008  model = model || this.model;
1009
1010  if (!model) {
1011    return options;
1012  }
1013
1014  if (!('safe' in options) && model.schema.options.safe) {
1015    options.safe = model.schema.options.safe;
1016  }
1017
1018  if (!('readPreference' in options) && model.schema.options.read) {
1019    options.readPreference = model.schema.options.read;
1020  }
1021
1022  return options;
1023};
1024
1025/**
1026 * Sets the lean option.
1027 *
1028 * Documents returned from queries with the `lean` option enabled are plain javascript objects, not [MongooseDocuments](#document-js). They have no `save` method, getters/setters or other Mongoose magic applied.
1029 *
1030 * ####Example:
1031 *
1032 *     new Query().lean() // true
1033 *     new Query().lean(true)
1034 *     new Query().lean(false)
1035 *
1036 *     Model.find().lean().exec(function (err, docs) {
1037 *       docs[0] instanceof mongoose.Document // false
1038 *     });
1039 *
1040 * This is a [great](https://groups.google.com/forum/#!topic/mongoose-orm/u2_DzDydcnA/discussion) option in high-performance read-only scenarios, especially when combined with [stream](#query_Query-stream).
1041 *
1042 * @param {Boolean} bool defaults to true
1043 * @return {Query} this
1044 * @api public
1045 */
1046
1047Query.prototype.lean = function(v) {
1048  this._mongooseOptions.lean = arguments.length ? !!v : true;
1049  return this;
1050};
1051
1052/**
1053 * Thunk around find()
1054 *
1055 * @param {Function} [callback]
1056 * @return {Query} this
1057 * @api private
1058 */
1059Query.prototype._find = function(callback) {
1060  if (this._castError) {
1061    callback(this._castError);
1062    return this;
1063  }
1064
1065  this._applyPaths();
1066  this._fields = this._castFields(this._fields);
1067
1068  var fields = this._fieldsForExec();
1069  var options = this._mongooseOptions;
1070  var _this = this;
1071
1072  var cb = function(err, docs) {
1073    if (err) {
1074      return callback(err);
1075    }
1076
1077    if (docs.length === 0) {
1078      return callback(null, docs);
1079    }
1080
1081    if (!options.populate) {
1082      return options.lean === true
1083          ? callback(null, docs)
1084          : completeMany(_this.model, docs, fields, _this, null, callback);
1085    }
1086
1087    var pop = helpers.preparePopulationOptionsMQ(_this, options);
1088    pop.__noPromise = true;
1089    _this.model.populate(docs, pop, function(err, docs) {
1090      if (err) return callback(err);
1091      return options.lean === true
1092          ? callback(null, docs)
1093          : completeMany(_this.model, docs, fields, _this, pop, callback);
1094    });
1095  };
1096
1097  return Query.base.find.call(this, {}, cb);
1098};
1099
1100/**
1101 * Finds documents.
1102 *
1103 * When no `callback` is passed, the query is not executed. When the query is executed, the result will be an array of documents.
1104 *
1105 * ####Example
1106 *
1107 *     query.find({ name: 'Los Pollos Hermanos' }).find(callback)
1108 *
1109 * @param {Object} [criteria] mongodb selector
1110 * @param {Function} [callback]
1111 * @return {Query} this
1112 * @api public
1113 */
1114
1115Query.prototype.find = function(conditions, callback) {
1116  if (typeof conditions === 'function') {
1117    callback = conditions;
1118    conditions = {};
1119  }
1120
1121  conditions = utils.toObject(conditions);
1122
1123  if (mquery.canMerge(conditions)) {
1124    this.merge(conditions);
1125  }
1126
1127  prepareDiscriminatorCriteria(this);
1128
1129  try {
1130    this.cast(this.model);
1131    this._castError = null;
1132  } catch (err) {
1133    this._castError = err;
1134  }
1135
1136  // if we don't have a callback, then just return the query object
1137  if (!callback) {
1138    return Query.base.find.call(this);
1139  }
1140
1141  this._find(callback);
1142
1143  return this;
1144};
1145
1146/*!
1147 * hydrates many documents
1148 *
1149 * @param {Model} model
1150 * @param {Array} docs
1151 * @param {Object} fields
1152 * @param {Query} self
1153 * @param {Array} [pop] array of paths used in population
1154 * @param {Function} callback
1155 */
1156
1157function completeMany(model, docs, fields, self, pop, callback) {
1158  var arr = [];
1159  var count = docs.length;
1160  var len = count;
1161  var opts = pop ?
1162  {populated: pop}
1163      : undefined;
1164  function init(err) {
1165    if (err) return callback(err);
1166    --count || callback(null, arr);
1167  }
1168  for (var i = 0; i < len; ++i) {
1169    arr[i] = helpers.createModel(model, docs[i], fields);
1170    arr[i].init(docs[i], opts, init);
1171  }
1172}
1173
1174/**
1175 * Thunk around findOne()
1176 *
1177 * @param {Function} [callback]
1178 * @see findOne http://docs.mongodb.org/manual/reference/method/db.collection.findOne/
1179 * @api private
1180 */
1181
1182Query.prototype._findOne = function(callback) {
1183  if (this._castError) {
1184    return callback(this._castError);
1185  }
1186
1187  this._applyPaths();
1188  this._fields = this._castFields(this._fields);
1189
1190  var options = this._mongooseOptions;
1191  var projection = this._fieldsForExec();
1192  var _this = this;
1193
1194  // don't pass in the conditions because we already merged them in
1195  Query.base.findOne.call(_this, {}, function(err, doc) {
1196    if (err) {
1197      return callback(err);
1198    }
1199    if (!doc) {
1200      return callback(null, null);
1201    }
1202
1203    if (!options.populate) {
1204      return options.lean === true
1205          ? callback(null, doc)
1206          : completeOne(_this.model, doc, null, projection, _this, null, callback);
1207    }
1208
1209    var pop = helpers.preparePopulationOptionsMQ(_this, options);
1210    pop.__noPromise = true;
1211    _this.model.populate(doc, pop, function(err, doc) {
1212      if (err) {
1213        return callback(err);
1214      }
1215      return options.lean === true
1216          ? callback(null, doc)
1217          : completeOne(_this.model, doc, null, projection, _this, pop, callback);
1218    });
1219  });
1220};
1221
1222/**
1223 * Declares the query a findOne operation. When executed, the first found document is passed to the callback.
1224 *
1225 * Passing a `callback` executes the query. The result of the query is a single document.
1226 *
1227 * ####Example
1228 *
1229 *     var query  = Kitten.where({ color: 'white' });
1230 *     query.findOne(function (err, kitten) {
1231 *       if (err) return handleError(err);
1232 *       if (kitten) {
1233 *         // doc may be null if no document matched
1234 *       }
1235 *     });
1236 *
1237 * @param {Object|Query} [criteria] mongodb selector
1238 * @param {Object} [projection] optional fields to return
1239 * @param {Function} [callback]
1240 * @return {Query} this
1241 * @see findOne http://docs.mongodb.org/manual/reference/method/db.collection.findOne/
1242 * @see Query.select #query_Query-select
1243 * @api public
1244 */
1245
1246Query.prototype.findOne = function(conditions, projection, options, callback) {
1247  if (typeof conditions === 'function') {
1248    callback = conditions;
1249    conditions = null;
1250    projection = null;
1251    options = null;
1252  } else if (typeof projection === 'function') {
1253    callback = projection;
1254    options = null;
1255    projection = null;
1256  } else if (typeof options === 'function') {
1257    callback = options;
1258    options = null;
1259  }
1260
1261  // make sure we don't send in the whole Document to merge()
1262  conditions = utils.toObject(conditions);
1263
1264  this.op = 'findOne';
1265
1266  if (options) {
1267    this.setOptions(options);
1268  }
1269
1270  if (projection) {
1271    this.select(projection);
1272  }
1273
1274  if (mquery.canMerge(conditions)) {
1275    this.merge(conditions);
1276  } else if (conditions != null) {
1277    throw new Error('Invalid argument to findOne(): ' +
1278      util.inspect(conditions));
1279  }
1280
1281  prepareDiscriminatorCriteria(this);
1282
1283  try {
1284    this.cast(this.model);
1285    this._castError = null;
1286  } catch (err) {
1287    this._castError = err;
1288  }
1289
1290  if (!callback) {
1291    // already merged in the conditions, don't need to send them in.
1292    return Query.base.findOne.call(this);
1293  }
1294
1295  this._findOne(callback);
1296
1297  return this;
1298};
1299
1300/**
1301 * Thunk around count()
1302 *
1303 * @param {Function} [callback]
1304 * @see count http://docs.mongodb.org/manual/reference/method/db.collection.count/
1305 * @api private
1306 */
1307
1308Query.prototype._count = function(callback) {
1309  try {
1310    this.cast(this.model);
1311  } catch (err) {
1312    process.nextTick(function() {
1313      callback(err);
1314    });
1315    return this;
1316  }
1317
1318  var conds = this._conditions;
1319  var options = this._optionsForExec();
1320
1321  this._collection.count(conds, options, utils.tick(callback));
1322};
1323
1324/**
1325 * Specifying this query as a `count` query.
1326 *
1327 * Passing a `callback` executes the query.
1328 *
1329 * ####Example:
1330 *
1331 *     var countQuery = model.where({ 'color': 'black' }).count();
1332 *
1333 *     query.count({ color: 'black' }).count(callback)
1334 *
1335 *     query.count({ color: 'black' }, callback)
1336 *
1337 *     query.where('color', 'black').count(function (err, count) {
1338 *       if (err) return handleError(err);
1339 *       console.log('there are %d kittens', count);
1340 *     })
1341 *
1342 * @param {Object} [criteria] mongodb selector
1343 * @param {Function} [callback]
1344 * @return {Query} this
1345 * @see count http://docs.mongodb.org/manual/reference/method/db.collection.count/
1346 * @api public
1347 */
1348
1349Query.prototype.count = function(conditions, callback) {
1350  if (typeof conditions === 'function') {
1351    callback = conditions;
1352    conditions = undefined;
1353  }
1354
1355  if (mquery.canMerge(conditions)) {
1356    this.merge(conditions);
1357  }
1358
1359  this.op = 'count';
1360  if (!callback) {
1361    return this;
1362  }
1363
1364  this._count(callback);
1365
1366  return this;
1367};
1368
1369/**
1370 * Declares or executes a distict() operation.
1371 *
1372 * Passing a `callback` executes the query.
1373 *
1374 * ####Example
1375 *
1376 *     distinct(field, conditions, callback)
1377 *     distinct(field, conditions)
1378 *     distinct(field, callback)
1379 *     distinct(field)
1380 *     distinct(callback)
1381 *     distinct()
1382 *
1383 * @param {String} [field]
1384 * @param {Object|Query} [criteria]
1385 * @param {Function} [callback]
1386 * @return {Query} this
1387 * @see distinct http://docs.mongodb.org/manual/reference/method/db.collection.distinct/
1388 * @api public
1389 */
1390
1391Query.prototype.distinct = function(field, conditions, callback) {
1392  if (!callback) {
1393    if (typeof conditions === 'function') {
1394      callback = conditions;
1395      conditions = undefined;
1396    } else if (typeof field === 'function') {
1397      callback = field;
1398      field = undefined;
1399      conditions = undefined;
1400    }
1401  }
1402
1403  conditions = utils.toObject(conditions);
1404
1405  if (mquery.canMerge(conditions)) {
1406    this.merge(conditions);
1407  }
1408
1409  try {
1410    this.cast(this.model);
1411  } catch (err) {
1412    if (!callback) {
1413      throw err;
1414    }
1415    callback(err);
1416    return this;
1417  }
1418
1419  return Query.base.distinct.call(this, {}, field, callback);
1420};
1421
1422/**
1423 * Sets the sort order
1424 *
1425 * If an object is passed, values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`.
1426 *
1427 * If a string is passed, it must be a space delimited list of path names. The
1428 * sort order of each path is ascending unless the path name is prefixed with `-`
1429 * which will be treated as descending.
1430 *
1431 * ####Example
1432 *
1433 *     // sort by "field" ascending and "test" descending
1434 *     query.sort({ field: 'asc', test: -1 });
1435 *
1436 *     // equivalent
1437 *     query.sort('field -test');
1438 *
1439 * ####Note
1440 *
1441 * Cannot be used with `distinct()`
1442 *
1443 * @param {Object|String} arg
1444 * @return {Query} this
1445 * @see cursor.sort http://docs.mongodb.org/manual/reference/method/cursor.sort/
1446 * @api public
1447 */
1448
1449Query.prototype.sort = function(arg) {
1450  var nArg = {};
1451
1452  if (arguments.length > 1) {
1453    throw new Error('sort() only takes 1 Argument');
1454  }
1455
1456  if (Array.isArray(arg)) {
1457    // time to deal with the terrible syntax
1458    for (var i = 0; i < arg.length; i++) {
1459      if (!Array.isArray(arg[i])) throw new Error('Invalid sort() argument.');
1460      nArg[arg[i][0]] = arg[i][1];
1461    }
1462  } else {
1463    nArg = arg;
1464  }
1465
1466  return Query.base.sort.call(this, nArg);
1467};
1468
1469/**
1470 * Declare and/or execute this query as a remove() operation.
1471 *
1472 * ####Example
1473 *
1474 *     Model.remove({ artist: 'Anne Murray' }, callback)
1475 *
1476 * ####Note
1477 *
1478 * The operation is only executed when a callback is passed. To force execution without a callback, you must first call `remove()` and then execute it by using the `exec()` method.
1479 *
1480 *     // not executed
1481 *     var query = Model.find().remove({ name: 'Anne Murray' })
1482 *
1483 *     // executed
1484 *     query.remove({ name: 'Anne Murray' }, callback)
1485 *     query.remove({ name: 'Anne Murray' }).remove(callback)
1486 *
1487 *     // executed without a callback
1488 *     query.exec()
1489 *
1490 *     // summary
1491 *     query.remove(conds, fn); // executes
1492 *     query.remove(conds)
1493 *     query.remove(fn) // executes
1494 *     query.remove()
1495 *
1496 * @param {Object|Query} [criteria] mongodb selector
1497 * @param {Function} [callback]
1498 * @return {Query} this
1499 * @see remove http://docs.mongodb.org/manual/reference/method/db.collection.remove/
1500 * @api public
1501 */
1502
1503Query.prototype.remove = function(cond, callback) {
1504  if (typeof cond === 'function') {
1505    callback = cond;
1506    cond = null;
1507  }
1508
1509  var cb = typeof callback === 'function';
1510
1511  try {
1512    this.cast(this.model);
1513  } catch (err) {
1514    if (cb) return process.nextTick(callback.bind(null, err));
1515    return this;
1516  }
1517
1518  return Query.base.remove.call(this, cond, callback);
1519};
1520
1521/*!
1522 * hydrates a document
1523 *
1524 * @param {Model} model
1525 * @param {Document} doc
1526 * @param {Object} res 3rd parameter to callback
1527 * @param {Object} fields
1528 * @param {Query} self
1529 * @param {Array} [pop] array of paths used in population
1530 * @param {Function} callback
1531 */
1532
1533function completeOne(model, doc, res, fields, self, pop, callback) {
1534  var opts = pop ?
1535  {populated: pop}
1536      : undefined;
1537
1538  var casted = helpers.createModel(model, doc, fields);
1539  casted.init(doc, opts, function(err) {
1540    if (err) {
1541      return callback(err);
1542    }
1543    if (res) {
1544      return callback(null, casted, res);
1545    }
1546    callback(null, casted);
1547  });
1548}
1549
1550/*!
1551 * If the model is a discriminator type and not root, then add the key & value to the criteria.
1552 */
1553
1554function prepareDiscriminatorCriteria(query) {
1555  if (!query || !query.model || !query.model.schema) {
1556    return;
1557  }
1558
1559  var schema = query.model.schema;
1560
1561  if (schema && schema.discriminatorMapping && !schema.discriminatorMapping.isRoot) {
1562    query._conditions[schema.discriminatorMapping.key] = schema.discriminatorMapping.value;
1563  }
1564}
1565
1566/**
1567 * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) update command.
1568 *
1569 * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes immediately if `callback` is passed.
1570 *
1571 * ####Available options
1572 *
1573 * - `new`: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0)
1574 * - `upsert`: bool - creates the object if it doesn't exist. defaults to false.
1575 * - `fields`: {Object|String} - Field selection. Equivalent to `.select(fields).findOneAndUpdate()`
1576 * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
1577 * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
1578 * - `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.
1579 * - `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/).
1580 * - `passRawResult`: if true, passes the [raw result from the MongoDB driver as the third callback parameter](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
1581 * - `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.
1582 *
1583 * ####Callback Signature
1584 *     function(error, doc) {
1585 *       // error: any errors that occurred
1586 *       // doc: the document before updates are applied if `new: false`, or after updates if `new = true`
1587 *     }
1588 *
1589 * ####Examples
1590 *
1591 *     query.findOneAndUpdate(conditions, update, options, callback) // executes
1592 *     query.findOneAndUpdate(conditions, update, options)  // returns Query
1593 *     query.findOneAndUpdate(conditions, update, callback) // executes
1594 *     query.findOneAndUpdate(conditions, update)           // returns Query
1595 *     query.findOneAndUpdate(update, callback)             // returns Query
1596 *     query.findOneAndUpdate(update)                       // returns Query
1597 *     query.findOneAndUpdate(callback)                     // executes
1598 *     query.findOneAndUpdate()                             // returns Query
1599 *
1600 * @method findOneAndUpdate
1601 * @memberOf Query
1602 * @param {Object|Query} [query]
1603 * @param {Object} [doc]
1604 * @param {Object} [options]
1605 * @param {Function} [callback]
1606 * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command
1607 * @return {Query} this
1608 * @api public
1609 */
1610
1611Query.prototype.findOneAndUpdate = function(criteria, doc, options, callback) {
1612  this.op = 'findOneAndUpdate';
1613  this._validate();
1614
1615  switch (arguments.length) {
1616    case 3:
1617      if (typeof options === 'function') {
1618        callback = options;
1619        options = {};
1620      }
1621      break;
1622    case 2:
1623      if (typeof doc === 'function') {
1624        callback = doc;
1625        doc = criteria;
1626        criteria = undefined;
1627      }
1628      options = undefined;
1629      break;
1630    case 1:
1631      if (typeof criteria === 'function') {
1632        callback = criteria;
1633        criteria = options = doc = undefined;
1634      } else {
1635        doc = criteria;
1636        criteria = options = undefined;
1637      }
1638  }
1639
1640  if (mquery.canMerge(criteria)) {
1641    this.merge(criteria);
1642  }
1643
1644  // apply doc
1645  if (doc) {
1646    this._mergeUpdate(doc);
1647  }
1648
1649  if (options) {
1650    options = utils.clone(options, { retainKeyOrder: true });
1651    if (options.projection) {
1652      this.select(options.projection);
1653      delete options.projection;
1654    }
1655    if (options.fields) {
1656      this.select(options.fields);
1657      delete options.fields;
1658    }
1659
1660    this.setOptions(options);
1661  }
1662
1663  if (!callback) {
1664    return this;
1665  }
1666
1667  return this._findOneAndUpdate(callback);
1668};
1669
1670/**
1671 * Thunk around findOneAndUpdate()
1672 *
1673 * @param {Function} [callback]
1674 * @api private
1675 */
1676
1677Query.prototype._findOneAndUpdate = function(callback) {
1678  this._findAndModify('update', callback);
1679  return this;
1680};
1681
1682/**
1683 * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) remove command.
1684 *
1685 * Finds a matching document, removes it, passing the found document (if any) to the callback. Executes immediately if `callback` is passed.
1686 *
1687 * ####Available options
1688 *
1689 * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
1690 * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
1691 * - `passRawResult`: if true, passes the [raw result from the MongoDB driver as the third callback parameter](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
1692 *
1693 * ####Callback Signature
1694 *     function(error, doc, result) {
1695 *       // error: any errors that occurred
1696 *       // doc: the document before updates are applied if `new: false`, or after updates if `new = true`
1697 *       // result: [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
1698 *     }
1699 *
1700 * ####Examples
1701 *
1702 *     A.where().findOneAndRemove(conditions, options, callback) // executes
1703 *     A.where().findOneAndRemove(conditions, options)  // return Query
1704 *     A.where().findOneAndRemove(conditions, callback) // executes
1705 *     A.where().findOneAndRemove(conditions) // returns Query
1706 *     A.where().findOneAndRemove(callback)   // executes
1707 *     A.where().findOneAndRemove()           // returns Query
1708 *
1709 * @method findOneAndRemove
1710 * @memberOf Query
1711 * @param {Object} [conditions]
1712 * @param {Object} [options]
1713 * @param {Function} [callback]
1714 * @return {Query} this
1715 * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command
1716 * @api public
1717 */
1718
1719Query.prototype.findOneAndRemove = function(conditions, options, callback) {
1720  this.op = 'findOneAndRemove';
1721  this._validate();
1722
1723  switch (arguments.length) {
1724    case 2:
1725      if (typeof options === 'function') {
1726        callback = options;
1727        options = {};
1728      }
1729      break;
1730    case 1:
1731      if (typeof conditions === 'function') {
1732        callback = conditions;
1733        conditions = undefined;
1734        options = undefined;
1735      }
1736      break;
1737  }
1738
1739  if (mquery.canMerge(conditions)) {
1740    this.merge(conditions);
1741  }
1742
1743  options && this.setOptions(options);
1744
1745  if (!callback) {
1746    return this;
1747  }
1748
1749  this._findOneAndRemove(callback);
1750
1751  return this;
1752};
1753
1754/**
1755 * Thunk around findOneAndRemove()
1756 *
1757 * @param {Function} [callback]
1758 * @return {Query} this
1759 * @api private
1760 */
1761Query.prototype._findOneAndRemove = function(callback) {
1762  Query.base.findOneAndRemove.call(this, callback);
1763};
1764
1765/**
1766 * Override mquery.prototype._findAndModify to provide casting etc.
1767 *
1768 * @param {String} type - either "remove" or "update"
1769 * @param {Function} callback
1770 * @api private
1771 */
1772
1773Query.prototype._findAndModify = function(type, callback) {
1774  if (typeof callback !== 'function') {
1775    throw new Error('Expected callback in _findAndModify');
1776  }
1777
1778  var model = this.model;
1779  var schema = model.schema;
1780  var _this = this;
1781  var castedQuery;
1782  var castedDoc;
1783  var fields;
1784  var opts;
1785  var doValidate;
1786
1787  castedQuery = castQuery(this);
1788  if (castedQuery instanceof Error) {
1789    return callback(castedQuery);
1790  }
1791
1792  opts = this._optionsForExec(model);
1793
1794  if ('strict' in opts) {
1795    this._mongooseOptions.strict = opts.strict;
1796  }
1797
1798  if (type === 'remove') {
1799    opts.remove = true;
1800  } else {
1801    if (!('new' in opts)) {
1802      opts.new = false;
1803    }
1804    if (!('upsert' in opts)) {
1805      opts.upsert = false;
1806    }
1807    if (opts.upsert || opts['new']) {
1808      opts.remove = false;
1809    }
1810
1811    castedDoc = castDoc(this, opts.overwrite);
1812    castedDoc = setDefaultsOnInsert(this, schema, castedDoc, opts);
1813    if (!castedDoc) {
1814      if (opts.upsert) {
1815        // still need to do the upsert to empty doc
1816        var doc = utils.clone(castedQuery);
1817        delete doc._id;
1818        castedDoc = {$set: doc};
1819      } else {
1820        return this.findOne(callback);
1821      }
1822    } else if (castedDoc instanceof Error) {
1823      return callback(castedDoc);
1824    } else {
1825      // In order to make MongoDB 2.6 happy (see
1826      // https://jira.mongodb.org/browse/SERVER-12266 and related issues)
1827      // if we have an actual update document but $set is empty, junk the $set.
1828      if (castedDoc.$set && Object.keys(castedDoc.$set).length === 0) {
1829        delete castedDoc.$set;
1830      }
1831    }
1832
1833    doValidate = updateValidators(this, schema, castedDoc, opts);
1834  }
1835
1836  this._applyPaths();
1837
1838  var options = this._mongooseOptions;
1839
1840  if (this._fields) {
1841    fields = utils.clone(this._fields);
1842    opts.fields = this._castFields(fields);
1843    if (opts.fields instanceof Error) {
1844      return callback(opts.fields);
1845    }
1846  }
1847
1848  if (opts.sort) convertSortToArray(opts);
1849
1850  var cb = function(err, doc, res) {
1851    if (err) {
1852      return callback(err);
1853    }
1854
1855    if (!doc || (utils.isObject(doc) && Object.keys(doc).length === 0)) {
1856      if (opts.passRawResult) {
1857        return callback(null, null, res);
1858      }
1859      return callback(null, null);
1860    }
1861
1862    if (!opts.passRawResult) {
1863      res = null;
1864    }
1865
1866    if (!options.populate) {
1867      return options.lean === true
1868          ? callback(null, doc)
1869          : completeOne(_this.model, doc, res, fields, _this, null, callback);
1870    }
1871
1872    var pop = helpers.preparePopulationOptionsMQ(_this, options);
1873    pop.__noPromise = true;
1874    _this.model.populate(doc, pop, function(err, doc) {
1875      if (err) {
1876        return callback(err);
1877      }
1878
1879      return options.lean === true
1880          ? callback(null, doc)
1881          : completeOne(_this.model, doc, res, fields, _this, pop, callback);
1882    });
1883  };
1884
1885  if (opts.runValidators && doValidate) {
1886    var _callback = function(error) {
1887      if (error) {
1888        return callback(error);
1889      }
1890      _this._collection.findAndModify(castedQuery, castedDoc, opts, utils.tick(function(error, res) {
1891        return cb(error, res ? res.value : res, res);
1892      }));
1893    };
1894
1895    try {
1896      doValidate(_callback);
1897    } catch (error) {
1898      callback(error);
1899    }
1900  } else {
1901    this._collection.findAndModify(castedQuery, castedDoc, opts, utils.tick(function(error, res) {
1902      return cb(error, res ? res.value : res, res);
1903    }));
1904  }
1905
1906  return this;
1907};
1908
1909/**
1910 * Override mquery.prototype._mergeUpdate to handle mongoose objects in
1911 * updates.
1912 *
1913 * @param {Object} doc
1914 * @api private
1915 */
1916
1917Query.prototype._mergeUpdate = function(doc) {
1918  if (!this._update) this._update = {};
1919  if (doc instanceof Query) {
1920    if (doc._update) {
1921      utils.mergeClone(this._update, doc._update);
1922    }
1923  } else {
1924    utils.mergeClone(this._update, doc);
1925  }
1926};
1927
1928/*!
1929 * The mongodb driver 1.3.23 only supports the nested array sort
1930 * syntax. We must convert it or sorting findAndModify will not work.
1931 */
1932
1933function convertSortToArray(opts) {
1934  if (Array.isArray(opts.sort)) {
1935    return;
1936  }
1937  if (!utils.isObject(opts.sort)) {
1938    return;
1939  }
1940
1941  var sort = [];
1942
1943  for (var key in opts.sort) {
1944    if (utils.object.hasOwnProperty(opts.sort, key)) {
1945      sort.push([key, opts.sort[key]]);
1946    }
1947  }
1948
1949  opts.sort = sort;
1950}
1951
1952/**
1953 * Internal thunk for .update()
1954 *
1955 * @param {Function} callback
1956 * @see Model.update #model_Model.update
1957 * @api private
1958 */
1959Query.prototype._execUpdate = function(callback) {
1960  var schema = this.model.schema;
1961  var doValidate;
1962  var _this;
1963
1964  var castedQuery = this._conditions;
1965  var castedDoc = this._update;
1966  var options = this.options;
1967
1968  if (this._castError) {
1969    callback(this._castError);
1970    return this;
1971  }
1972
1973  if (this.options.runValidators) {
1974    _this = this;
1975    doValidate = updateValidators(this, schema, castedDoc, options);
1976    var _callback = function(err) {
1977      if (err) {
1978        return callback(err);
1979      }
1980
1981      Query.base.update.call(_this, castedQuery, castedDoc, options, callback);
1982    };
1983    try {
1984      doValidate(_callback);
1985    } catch (err) {
1986      process.nextTick(function() {
1987        callback(err);
1988      });
1989    }
1990    return this;
1991  }
1992
1993  Query.base.update.call(this, castedQuery, castedDoc, options, callback);
1994  return this;
1995};
1996
1997/**
1998 * Declare and/or execute this query as an update() operation.
1999 *
2000 * _All paths passed that are not $atomic operations will become $set ops._
2001 *
2002 * ####Example
2003 *
2004 *     Model.where({ _id: id }).update({ title: 'words' })
2005 *
2006 *     // becomes
2007 *
2008 *     Model.where({ _id: id }).update({ $set: { title: 'words' }})
2009 *
2010 * ####Valid options:
2011 *
2012 *  - `safe` (boolean) safe mode (defaults to value set in schema (true))
2013 *  - `upsert` (boolean) whether to create the doc if it doesn't match (false)
2014 *  - `multi` (boolean) whether multiple documents should be updated (false)
2015 *  - `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.
2016 *  - `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/).
2017 *  - `strict` (boolean) overrides the `strict` option for this update
2018 *  - `overwrite` (boolean) disables update-only mode, allowing you to overwrite the doc (false)
2019 *  - `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.
2020 *
2021 * ####Note
2022 *
2023 * 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.
2024 *
2025 * ####Note
2026 *
2027 * 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.
2028 *
2029 *     var q = Model.where({ _id: id });
2030 *     q.update({ $set: { name: 'bob' }}).update(); // not executed
2031 *
2032 *     q.update({ $set: { name: 'bob' }}).exec(); // executed
2033 *
2034 *     // keys that are not $atomic ops become $set.
2035 *     // this executes the same command as the previous example.
2036 *     q.update({ name: 'bob' }).exec();
2037 *
2038 *     // overwriting with empty docs
2039 *     var q = Model.where({ _id: id }).setOptions({ overwrite: true })
2040 *     q.update({ }, callback); // executes
2041 *
2042 *     // multi update with overwrite to empty doc
2043 *     var q = Model.where({ _id: id });
2044 *     q.setOptions({ multi: true, overwrite: true })
2045 *     q.update({ });
2046 *     q.update(callback); // executed
2047 *
2048 *     // multi updates
2049 *     Model.where()
2050 *          .update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, callback)
2051 *
2052 *     // more multi updates
2053 *     Model.where()
2054 *          .setOptions({ multi: true })
2055 *          .update({ $set: { arr: [] }}, callback)
2056 *
2057 *     // single update by default
2058 *     Model.where({ email: 'address@example.com' })
2059 *          .update({ $inc: { counter: 1 }}, callback)
2060 *
2061 * API summary
2062 *
2063 *     update(criteria, doc, options, cb) // executes
2064 *     update(criteria, doc, options)
2065 *     update(criteria, doc, cb) // executes
2066 *     update(criteria, doc)
2067 *     update(doc, cb) // executes
2068 *     update(doc)
2069 *     update(cb) // executes
2070 *     update(true) // executes
2071 *     update()
2072 *
2073 * @param {Object} [criteria]
2074 * @param {Object} [doc] the update command
2075 * @param {Object} [options]
2076 * @param {Function} [callback]
2077 * @return {Query} this
2078 * @see Model.update #model_Model.update
2079 * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/
2080 * @api public
2081 */
2082
2083Query.prototype.update = function(conditions, doc, options, callback) {
2084  if (typeof options === 'function') {
2085    // .update(conditions, doc, callback)
2086    callback = options;
2087    options = null;
2088  } else if (typeof doc === 'function') {
2089    // .update(doc, callback);
2090    callback = doc;
2091    doc = conditions;
2092    conditions = {};
2093    options = null;
2094  } else if (typeof conditions === 'function') {
2095    // .update(callback)
2096    callback = conditions;
2097    conditions = undefined;
2098    doc = undefined;
2099    options = undefined;
2100  } else if (typeof conditions === 'object' && !doc && !options && !callback) {
2101    // .update(doc)
2102    doc = conditions;
2103    conditions = undefined;
2104    options = undefined;
2105    callback = undefined;
2106  }
2107
2108  // make sure we don't send in the whole Document to merge()
2109  conditions = utils.toObject(conditions);
2110
2111  var oldCb = callback;
2112  if (oldCb) {
2113    if (typeof oldCb === 'function') {
2114      callback = function(error, result) {
2115        oldCb(error, result ? result.result : {ok: 0, n: 0, nModified: 0});
2116      };
2117    } else {
2118      throw new Error('Invalid callback() argument.');
2119    }
2120  }
2121
2122  // strict is an option used in the update checking, make sure it gets set
2123  if (options) {
2124    if ('strict' in options) {
2125      this._mongooseOptions.strict = options.strict;
2126    }
2127  }
2128
2129  // if doc is undefined at this point, this means this function is being
2130  // executed by exec(not always see below). Grab the update doc from here in
2131  // order to validate
2132  // This could also be somebody calling update() or update({}). Probably not a
2133  // common use case, check for _update to make sure we don't do anything bad
2134  if (!doc && this._update) {
2135    doc = this._updateForExec();
2136  }
2137
2138  if (mquery.canMerge(conditions)) {
2139    this.merge(conditions);
2140  }
2141
2142  // validate the selector part of the query
2143  var castedQuery = castQuery(this);
2144  if (castedQuery instanceof Error) {
2145    this._castError = castedQuery;
2146    if (callback) {
2147      callback(castedQuery);
2148      return this;
2149    } else if (!options || !options.dontThrowCastError) {
2150      throw castedQuery;
2151    }
2152  }
2153
2154  // validate the update part of the query
2155  var castedDoc;
2156  try {
2157    var $options = {retainKeyOrder: true};
2158    if (options && options.minimize) {
2159      $options.minimize = true;
2160    }
2161    castedDoc = this._castUpdate(utils.clone(doc, $options),
2162        options && options.overwrite);
2163  } catch (err) {
2164    this._castError = castedQuery;
2165    if (callback) {
2166      callback(err);
2167      return this;
2168    } else if (!options || !options.dontThrowCastError) {
2169      throw err;
2170    }
2171  }
2172
2173  castedDoc = setDefaultsOnInsert(this, this.schema, castedDoc, options);
2174  if (!castedDoc) {
2175    // Make sure promises know that this is still an update, see gh-2796
2176    this.op = 'update';
2177    callback && callback(null);
2178    return this;
2179  }
2180
2181  if (utils.isObject(options)) {
2182    this.setOptions(options);
2183  }
2184
2185  if (!this._update) this._update = castedDoc;
2186
2187  // Hooks
2188  if (callback) {
2189    return this._execUpdate(callback);
2190  }
2191
2192  return Query.base.update.call(this, castedQuery, castedDoc, options, callback);
2193};
2194
2195/**
2196 * Executes the query
2197 *
2198 * ####Examples:
2199 *
2200 *     var promise = query.exec();
2201 *     var promise = query.exec('update');
2202 *
2203 *     query.exec(callback);
2204 *     query.exec('find', callback);
2205 *
2206 * @param {String|Function} [operation]
2207 * @param {Function} [callback]
2208 * @return {Promise}
2209 * @api public
2210 */
2211
2212Query.prototype.exec = function exec(op, callback) {
2213  var Promise = PromiseProvider.get();
2214  var _this = this;
2215
2216  if (typeof op === 'function') {
2217    callback = op;
2218    op = null;
2219  } else if (typeof op === 'string') {
2220    this.op = op;
2221  }
2222
2223  return new Promise.ES6(function(resolve, reject) {
2224    if (!_this.op) {
2225      callback && callback(null, undefined);
2226      resolve();
2227      return;
2228    }
2229
2230    _this[_this.op].call(_this, function(error, res) {
2231      if (error) {
2232        callback && callback(error);
2233        reject(error);
2234        return;
2235      }
2236      callback && callback.apply(null, arguments);
2237      resolve(res);
2238    });
2239  });
2240};
2241
2242/**
2243 * Executes the query returning a `Promise` which will be
2244 * resolved with either the doc(s) or rejected with the error.
2245 *
2246 * @param {Function} [resolve]
2247 * @param {Function} [reject]
2248 * @return {Promise}
2249 * @api public
2250 */
2251
2252Query.prototype.then = function(resolve, reject) {
2253  return this.exec().then(resolve, reject);
2254};
2255
2256/**
2257 * Executes the query returning a `Promise` which will be
2258 * resolved with either the doc(s) or rejected with the error.
2259 * Like `.then()`, but only takes a rejection handler.
2260 *
2261 * @param {Function} [reject]
2262 * @return {Promise}
2263 * @api public
2264 */
2265
2266Query.prototype.catch = function(reject) {
2267  return this.exec().then(null, reject);
2268};
2269
2270/**
2271 * Finds the schema for `path`. This is different than
2272 * calling `schema.path` as it also resolves paths with
2273 * positional selectors (something.$.another.$.path).
2274 *
2275 * @param {String} path
2276 * @api private
2277 */
2278
2279Query.prototype._getSchema = function _getSchema(path) {
2280  return this.model._getSchema(path);
2281};
2282
2283/*!
2284 * These operators require casting docs
2285 * to real Documents for Update operations.
2286 */
2287
2288var castOps = {
2289  $push: 1,
2290  $pushAll: 1,
2291  $addToSet: 1,
2292  $set: 1
2293};
2294
2295/*!
2296 * These operators should be cast to numbers instead
2297 * of their path schema type.
2298 */
2299
2300var numberOps = {
2301  $pop: 1,
2302  $unset: 1,
2303  $inc: 1
2304};
2305
2306/**
2307 * Casts obj for an update command.
2308 *
2309 * @param {Object} obj
2310 * @return {Object} obj after casting its values
2311 * @api private
2312 */
2313
2314Query.prototype._castUpdate = function _castUpdate(obj, overwrite) {
2315  if (!obj) {
2316    return undefined;
2317  }
2318
2319  var ops = Object.keys(obj);
2320  var i = ops.length;
2321  var ret = {};
2322  var hasKeys;
2323  var val;
2324  var hasDollarKey = false;
2325
2326  while (i--) {
2327    var op = ops[i];
2328    // if overwrite is set, don't do any of the special $set stuff
2329    if (op[0] !== '$' && !overwrite) {
2330      // fix up $set sugar
2331      if (!ret.$set) {
2332        if (obj.$set) {
2333          ret.$set = obj.$set;
2334        } else {
2335          ret.$set = {};
2336        }
2337      }
2338      ret.$set[op] = obj[op];
2339      ops.splice(i, 1);
2340      if (!~ops.indexOf('$set')) ops.push('$set');
2341    } else if (op === '$set') {
2342      if (!ret.$set) {
2343        ret[op] = obj[op];
2344      }
2345    } else {
2346      ret[op] = obj[op];
2347    }
2348  }
2349
2350  // cast each value
2351  i = ops.length;
2352
2353  // if we get passed {} for the update, we still need to respect that when it
2354  // is an overwrite scenario
2355  if (overwrite) {
2356    hasKeys = true;
2357  }
2358
2359  while (i--) {
2360    op = ops[i];
2361    val = ret[op];
2362    hasDollarKey = hasDollarKey || op.charAt(0) === '$';
2363    if (val &&
2364        val.constructor.name === 'Object' &&
2365        (!overwrite || hasDollarKey)) {
2366      hasKeys |= this._walkUpdatePath(val, op);
2367    } else if (overwrite && ret.constructor.name === 'Object') {
2368      // if we are just using overwrite, cast the query and then we will
2369      // *always* return the value, even if it is an empty object. We need to
2370      // set hasKeys above because we need to account for the case where the
2371      // user passes {} and wants to clobber the whole document
2372      // Also, _walkUpdatePath expects an operation, so give it $set since that
2373      // is basically what we're doing
2374      this._walkUpdatePath(ret, '$set');
2375    } else {
2376      var msg = 'Invalid atomic update value for ' + op + '. '
2377          + 'Expected an object, received ' + typeof val;
2378      throw new Error(msg);
2379    }
2380  }
2381
2382  return hasKeys && ret;
2383};
2384
2385/**
2386 * Walk each path of obj and cast its values
2387 * according to its schema.
2388 *
2389 * @param {Object} obj - part of a query
2390 * @param {String} op - the atomic operator ($pull, $set, etc)
2391 * @param {String} pref - path prefix (internal only)
2392 * @return {Bool} true if this path has keys to update
2393 * @api private
2394 */
2395
2396Query.prototype._walkUpdatePath = function _walkUpdatePath(obj, op, pref) {
2397  var prefix = pref ? pref + '.' : '',
2398      keys = Object.keys(obj),
2399      i = keys.length,
2400      hasKeys = false,
2401      schema,
2402      key,
2403      val;
2404
2405  var useNestedStrict = this.schema.options.useNestedStrict;
2406
2407  while (i--) {
2408    key = keys[i];
2409    val = obj[key];
2410
2411    if (val && val.constructor.name === 'Object') {
2412      // watch for embedded doc schemas
2413      schema = this._getSchema(prefix + key);
2414      if (schema && schema.caster && op in castOps) {
2415        // embedded doc schema
2416        hasKeys = true;
2417
2418        if ('$each' in val) {
2419          obj[key] = {
2420            $each: this._castUpdateVal(schema, val.$each, op)
2421          };
2422
2423          if (val.$slice != null) {
2424            obj[key].$slice = val.$slice | 0;
2425          }
2426
2427          if (val.$sort) {
2428            obj[key].$sort = val.$sort;
2429          }
2430
2431          if (!!val.$position || val.$position === 0) {
2432            obj[key].$position = val.$position;
2433          }
2434        } else {
2435          obj[key] = this._castUpdateVal(schema, val, op);
2436        }
2437      } else if (op === '$currentDate') {
2438        // $currentDate can take an object
2439        obj[key] = this._castUpdateVal(schema, val, op);
2440        hasKeys = true;
2441      } else if (op === '$set' && schema) {
2442        obj[key] = this._castUpdateVal(schema, val, op);
2443        hasKeys = true;
2444      } else {
2445        var pathToCheck = (prefix + key);
2446        var v = this.model.schema._getPathType(pathToCheck);
2447        var _strict = 'strict' in this._mongooseOptions ?
2448          this._mongooseOptions.strict :
2449          ((useNestedStrict && v.schema) || this.schema).options.strict;
2450        if (v.pathType === 'undefined') {
2451          if (_strict === 'throw') {
2452            throw new StrictModeError(pathToCheck);
2453          } else if (_strict) {
2454            delete obj[key];
2455            continue;
2456          }
2457        }
2458
2459        // gh-2314
2460        // we should be able to set a schema-less field
2461        // to an empty object literal
2462        hasKeys |= this._walkUpdatePath(val, op, prefix + key) ||
2463            (utils.isObject(val) && Object.keys(val).length === 0);
2464      }
2465    } else {
2466      var checkPath = (key === '$each' || key === '$or' || key === '$and') ?
2467        pref : prefix + key;
2468      schema = this._getSchema(checkPath);
2469
2470      var pathDetails = this.model.schema._getPathType(checkPath);
2471      var isStrict = 'strict' in this._mongooseOptions ?
2472        this._mongooseOptions.strict :
2473        ((useNestedStrict && pathDetails.schema) || this.schema).options.strict;
2474
2475      var skip = isStrict &&
2476          !schema &&
2477          !/real|nested/.test(pathDetails.pathType);
2478
2479      if (skip) {
2480        if (isStrict === 'throw') {
2481          throw new StrictModeError(prefix + key);
2482        } else {
2483          delete obj[key];
2484        }
2485      } else {
2486        // gh-1845 temporary fix: ignore $rename. See gh-3027 for tracking
2487        // improving this.
2488        if (op === '$rename') {
2489          hasKeys = true;
2490          continue;
2491        }
2492
2493        hasKeys = true;
2494        obj[key] = this._castUpdateVal(schema, val, op, key);
2495      }
2496    }
2497  }
2498  return hasKeys;
2499};
2500
2501/**
2502 * Casts `val` according to `schema` and atomic `op`.
2503 *
2504 * @param {Schema} schema
2505 * @param {Object} val
2506 * @param {String} op - the atomic operator ($pull, $set, etc)
2507 * @param {String} [$conditional]
2508 * @api private
2509 */
2510
2511Query.prototype._castUpdateVal = function _castUpdateVal(schema, val, op, $conditional) {
2512  if (!schema) {
2513    // non-existing schema path
2514    return op in numberOps
2515        ? Number(val)
2516        : val;
2517  }
2518
2519  var cond = schema.caster && op in castOps &&
2520      (utils.isObject(val) || Array.isArray(val));
2521  if (cond) {
2522    // Cast values for ops that add data to MongoDB.
2523    // Ensures embedded documents get ObjectIds etc.
2524    var tmp = schema.cast(val);
2525    if (Array.isArray(val)) {
2526      val = tmp;
2527    } else if (schema.caster.$isSingleNested) {
2528      val = tmp;
2529    } else {
2530      val = tmp[0];
2531    }
2532  }
2533
2534  if (op in numberOps) {
2535    if (op === '$inc') {
2536      return schema.castForQuery(val);
2537    }
2538    return Number(val);
2539  }
2540  if (op === '$currentDate') {
2541    if (typeof val === 'object') {
2542      return {$type: val.$type};
2543    }
2544    return Boolean(val);
2545  }
2546  if (/^\$/.test($conditional)) {
2547    return schema.castForQuery($conditional, val);
2548  }
2549
2550  return schema.castForQuery(val);
2551};
2552
2553/*!
2554 * castQuery
2555 * @api private
2556 */
2557
2558function castQuery(query) {
2559  try {
2560    return query.cast(query.model);
2561  } catch (err) {
2562    return err;
2563  }
2564}
2565
2566/*!
2567 * castDoc
2568 * @api private
2569 */
2570
2571function castDoc(query, overwrite) {
2572  try {
2573    return query._castUpdate(query._update, overwrite);
2574  } catch (err) {
2575    return err;
2576  }
2577}
2578
2579/**
2580 * Specifies paths which should be populated with other documents.
2581 *
2582 * ####Example:
2583 *
2584 *     Kitten.findOne().populate('owner').exec(function (err, kitten) {
2585 *       console.log(kitten.owner.name) // Max
2586 *     })
2587 *
2588 *     Kitten.find().populate({
2589 *         path: 'owner'
2590 *       , select: 'name'
2591 *       , match: { color: 'black' }
2592 *       , options: { sort: { name: -1 }}
2593 *     }).exec(function (err, kittens) {
2594 *       console.log(kittens[0].owner.name) // Zoopa
2595 *     })
2596 *
2597 *     // alternatively
2598 *     Kitten.find().populate('owner', 'name', null, {sort: { name: -1 }}).exec(function (err, kittens) {
2599 *       console.log(kittens[0].owner.name) // Zoopa
2600 *     })
2601 *
2602 * Paths are populated after the query executes and a response is received. A separate query is then executed for each path specified for population. After a response for each query has also been returned, the results are passed to the callback.
2603 *
2604 * @param {Object|String} path either the path to populate or an object specifying all parameters
2605 * @param {Object|String} [select] Field selection for the population query
2606 * @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.
2607 * @param {Object} [match] Conditions for the population query
2608 * @param {Object} [options] Options for the population query (sort, etc)
2609 * @see population ./populate.html
2610 * @see Query#select #query_Query-select
2611 * @see Model.populate #model_Model.populate
2612 * @return {Query} this
2613 * @api public
2614 */
2615
2616Query.prototype.populate = function() {
2617  var res = utils.populate.apply(null, arguments);
2618  var opts = this._mongooseOptions;
2619
2620  if (!utils.isObject(opts.populate)) {
2621    opts.populate = {};
2622  }
2623
2624  var pop = opts.populate;
2625
2626  for (var i = 0; i < res.length; ++i) {
2627    var path = res[i].path;
2628    if (pop[path] && pop[path].populate && res[i].populate) {
2629      res[i].populate = pop[path].populate.concat(res[i].populate);
2630    }
2631    pop[res[i].path] = res[i];
2632  }
2633
2634  return this;
2635};
2636
2637/**
2638 * Casts this query to the schema of `model`
2639 *
2640 * ####Note
2641 *
2642 * If `obj` is present, it is cast instead of this query.
2643 *
2644 * @param {Model} model
2645 * @param {Object} [obj]
2646 * @return {Object}
2647 * @api public
2648 */
2649
2650Query.prototype.cast = function(model, obj) {
2651  obj || (obj = this._conditions);
2652
2653  return cast(model.schema, obj);
2654};
2655
2656/**
2657 * Casts selected field arguments for field selection with mongo 2.2
2658 *
2659 *     query.select({ ids: { $elemMatch: { $in: [hexString] }})
2660 *
2661 * @param {Object} fields
2662 * @see https://github.com/Automattic/mongoose/issues/1091
2663 * @see http://docs.mongodb.org/manual/reference/projection/elemMatch/
2664 * @api private
2665 */
2666
2667Query.prototype._castFields = function _castFields(fields) {
2668  var selected,
2669      elemMatchKeys,
2670      keys,
2671      key,
2672      out,
2673      i;
2674
2675  if (fields) {
2676    keys = Object.keys(fields);
2677    elemMatchKeys = [];
2678    i = keys.length;
2679
2680    // collect $elemMatch args
2681    while (i--) {
2682      key = keys[i];
2683      if (fields[key].$elemMatch) {
2684        selected || (selected = {});
2685        selected[key] = fields[key];
2686        elemMatchKeys.push(key);
2687      }
2688    }
2689  }
2690
2691  if (selected) {
2692    // they passed $elemMatch, cast em
2693    try {
2694      out = this.cast(this.model, selected);
2695    } catch (err) {
2696      return err;
2697    }
2698
2699    // apply the casted field args
2700    i = elemMatchKeys.length;
2701    while (i--) {
2702      key = elemMatchKeys[i];
2703      fields[key] = out[key];
2704    }
2705  }
2706
2707  return fields;
2708};
2709
2710/**
2711 * Applies schematype selected options to this query.
2712 * @api private
2713 */
2714
2715Query.prototype._applyPaths = function applyPaths() {
2716  // determine if query is selecting or excluding fields
2717
2718  var fields = this._fields,
2719      exclude,
2720      keys,
2721      ki;
2722
2723  if (fields) {
2724    keys = Object.keys(fields);
2725    ki = keys.length;
2726
2727    while (ki--) {
2728      if (keys[ki][0] === '+') continue;
2729      exclude = fields[keys[ki]] === 0;
2730      break;
2731    }
2732  }
2733
2734  // if selecting, apply default schematype select:true fields
2735  // if excluding, apply schematype select:false fields
2736
2737  var selected = [],
2738      excluded = [],
2739      seen = [];
2740
2741  var analyzePath = function(path, type) {
2742    if (typeof type.selected !== 'boolean') return;
2743
2744    var plusPath = '+' + path;
2745    if (fields && plusPath in fields) {
2746      // forced inclusion
2747      delete fields[plusPath];
2748
2749      // if there are other fields being included, add this one
2750      // if no other included fields, leave this out (implied inclusion)
2751      if (exclude === false && keys.length > 1 && !~keys.indexOf(path)) {
2752        fields[path] = 1;
2753      }
2754
2755      return;
2756    }
2757
2758    // check for parent exclusions
2759    var root = path.split('.')[0];
2760    if (~excluded.indexOf(root)) return;
2761
2762    (type.selected ? selected : excluded).push(path);
2763  };
2764
2765  var analyzeSchema = function(schema, prefix) {
2766    prefix || (prefix = '');
2767
2768    // avoid recursion
2769    if (~seen.indexOf(schema)) return;
2770    seen.push(schema);
2771
2772    schema.eachPath(function(path, type) {
2773      if (prefix) path = prefix + '.' + path;
2774
2775      analyzePath(path, type);
2776
2777      // array of subdocs?
2778      if (type.schema) {
2779        analyzeSchema(type.schema, path);
2780      }
2781    });
2782  };
2783
2784  analyzeSchema(this.model.schema);
2785
2786  switch (exclude) {
2787    case true:
2788      excluded.length && this.select('-' + excluded.join(' -'));
2789      break;
2790    case false:
2791      if (this.model.schema && this.model.schema.paths['_id'] &&
2792          this.model.schema.paths['_id'].options && this.model.schema.paths['_id'].options.select === false) {
2793        selected.push('-_id');
2794      }
2795      selected.length && this.select(selected.join(' '));
2796      break;
2797    case undefined:
2798      // user didn't specify fields, implies returning all fields.
2799      // only need to apply excluded fields
2800      excluded.length && this.select('-' + excluded.join(' -'));
2801      break;
2802  }
2803  seen = excluded = selected = keys = fields = null;
2804};
2805
2806/**
2807 * Returns a Node.js 0.8 style [read stream](http://nodejs.org/docs/v0.8.21/api/stream.html#stream_readable_stream) interface.
2808 *
2809 * ####Example
2810 *
2811 *     // follows the nodejs 0.8 stream api
2812 *     Thing.find({ name: /^hello/ }).stream().pipe(res)
2813 *
2814 *     // manual streaming
2815 *     var stream = Thing.find({ name: /^hello/ }).stream();
2816 *
2817 *     stream.on('data', function (doc) {
2818 *       // do something with the mongoose document
2819 *     }).on('error', function (err) {
2820 *       // handle the error
2821 *     }).on('close', function () {
2822 *       // the stream is closed
2823 *     });
2824 *
2825 * ####Valid options
2826 *
2827 *   - `transform`: optional function which accepts a mongoose document. The return value of the function will be emitted on `data`.
2828 *
2829 * ####Example
2830 *
2831 *     // JSON.stringify all documents before emitting
2832 *     var stream = Thing.find().stream({ transform: JSON.stringify });
2833 *     stream.pipe(writeStream);
2834 *
2835 * @return {QueryStream}
2836 * @param {Object} [options]
2837 * @see QueryStream
2838 * @api public
2839 */
2840
2841Query.prototype.stream = function stream(opts) {
2842  this._applyPaths();
2843  this._fields = this._castFields(this._fields);
2844  return new QueryStream(this, opts);
2845};
2846Query.prototype.stream = util.deprecate(Query.prototype.stream, 'Mongoose: ' +
2847  'Query.prototype.stream() is deprecated in mongoose >= 4.5.0, ' +
2848  'use Query.prototype.cursor() instead');
2849
2850/**
2851 * Returns a wrapper around a [mongodb driver cursor](http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html).
2852 * A QueryCursor exposes a [Streams3](https://strongloop.com/strongblog/whats-new-io-js-beta-streams3/)-compatible
2853 * interface, as well as a `.next()` function.
2854 *
2855 * ####Example
2856 *
2857 *     // There are 2 ways to use a cursor. First, as a stream:
2858 *     Thing.
2859 *       find({ name: /^hello/ }).
2860 *       cursor().
2861 *       on('data', function(doc) { console.log(doc); }).
2862 *       on('end', function() { console.log('Done!'); });
2863 *
2864 *     // Or you can use `.next()` to manually get the next doc in the stream.
2865 *     // `.next()` returns a promise, so you can use promises or callbacks.
2866 *     var cursor = Thing.find({ name: /^hello/ }).cursor();
2867 *     cursor.next(function(error, doc) {
2868 *       console.log(doc);
2869 *     });
2870 *
2871 *     // Because `.next()` returns a promise, you can use co
2872 *     // to easily iterate through all documents without loading them
2873 *     // all into memory.
2874 *     co(function*() {
2875 *       const cursor = Thing.find({ name: /^hello/ }).cursor();
2876 *       for (let doc = yield cursor.next(); doc != null; doc = yield cursor.next()) {
2877 *         console.log(doc);
2878 *       }
2879 *     });
2880 *
2881 *
2882 * @return {QueryCursor}
2883 * @param {Object} [options]
2884 * @see QueryCursor
2885 * @api public
2886 */
2887
2888Query.prototype.cursor = function cursor(opts) {
2889  this._applyPaths();
2890  this._fields = this._castFields(this._fields);
2891  this.setOptions({ fields: this._fieldsForExec() });
2892  if (opts) {
2893    this.setOptions(opts);
2894  }
2895
2896  try {
2897    this.cast(this.model);
2898  } catch (err) {
2899    return (new QueryCursor(this, this.options))._markError(err);
2900  }
2901
2902  return new QueryCursor(this, this.options);
2903};
2904
2905// the rest of these are basically to support older Mongoose syntax with mquery
2906
2907/**
2908 * _DEPRECATED_ Alias of `maxScan`
2909 *
2910 * @deprecated
2911 * @see maxScan #query_Query-maxScan
2912 * @method maxscan
2913 * @memberOf Query
2914 */
2915
2916Query.prototype.maxscan = Query.base.maxScan;
2917
2918/**
2919 * Sets the tailable option (for use with capped collections).
2920 *
2921 * ####Example
2922 *
2923 *     query.tailable() // true
2924 *     query.tailable(true)
2925 *     query.tailable(false)
2926 *
2927 * ####Note
2928 *
2929 * Cannot be used with `distinct()`
2930 *
2931 * @param {Boolean} bool defaults to true
2932 * @param {Object} [opts] options to set
2933 * @param {Number} [opts.numberOfRetries] if cursor is exhausted, retry this many times before giving up
2934 * @param {Number} [opts.tailableRetryInterval] if cursor is exhausted, wait this many milliseconds before retrying
2935 * @see tailable http://docs.mongodb.org/manual/tutorial/create-tailable-cursor/
2936 * @api public
2937 */
2938
2939Query.prototype.tailable = function(val, opts) {
2940  // we need to support the tailable({ awaitdata : true }) as well as the
2941  // tailable(true, {awaitdata :true}) syntax that mquery does not support
2942  if (val && val.constructor.name === 'Object') {
2943    opts = val;
2944    val = true;
2945  }
2946
2947  if (val === undefined) {
2948    val = true;
2949  }
2950
2951  if (opts && typeof opts === 'object') {
2952    for (var key in opts) {
2953      if (key === 'awaitdata') {
2954        // For backwards compatibility
2955        this.options[key] = !!opts[key];
2956      } else {
2957        this.options[key] = opts[key];
2958      }
2959    }
2960  }
2961
2962  return Query.base.tailable.call(this, val);
2963};
2964
2965/**
2966 * Declares an intersects query for `geometry()`.
2967 *
2968 * ####Example
2969 *
2970 *     query.where('path').intersects().geometry({
2971 *         type: 'LineString'
2972 *       , coordinates: [[180.0, 11.0], [180, 9.0]]
2973 *     })
2974 *
2975 *     query.where('path').intersects({
2976 *         type: 'LineString'
2977 *       , coordinates: [[180.0, 11.0], [180, 9.0]]
2978 *     })
2979 *
2980 * ####NOTE:
2981 *
2982 * **MUST** be used after `where()`.
2983 *
2984 * ####NOTE:
2985 *
2986 * 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).
2987 *
2988 * @method intersects
2989 * @memberOf Query
2990 * @param {Object} [arg]
2991 * @return {Query} this
2992 * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/
2993 * @see geoIntersects http://docs.mongodb.org/manual/reference/operator/geoIntersects/
2994 * @api public
2995 */
2996
2997/**
2998 * Specifies a `$geometry` condition
2999 *
3000 * ####Example
3001 *
3002 *     var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]]
3003 *     query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA })
3004 *
3005 *     // or
3006 *     var polyB = [[ 0, 0 ], [ 1, 1 ]]
3007 *     query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB })
3008 *
3009 *     // or
3010 *     var polyC = [ 0, 0 ]
3011 *     query.where('loc').within().geometry({ type: 'Point', coordinates: polyC })
3012 *
3013 *     // or
3014 *     query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC })
3015 *
3016 * The argument is assigned to the most recent path passed to `where()`.
3017 *
3018 * ####NOTE:
3019 *
3020 * `geometry()` **must** come after either `intersects()` or `within()`.
3021 *
3022 * The `object` argument must contain `type` and `coordinates` properties.
3023 * - type {String}
3024 * - coordinates {Array}
3025 *
3026 * @method geometry
3027 * @memberOf Query
3028 * @param {Object} object Must contain a `type` property which is a String and a `coordinates` property which is an Array. See the examples.
3029 * @return {Query} this
3030 * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/
3031 * @see http://docs.mongodb.org/manual/release-notes/2.4/#new-geospatial-indexes-with-geojson-and-improved-spherical-geometry
3032 * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
3033 * @api public
3034 */
3035
3036/**
3037 * Specifies a `$near` or `$nearSphere` condition
3038 *
3039 * These operators return documents sorted by distance.
3040 *
3041 * ####Example
3042 *
3043 *     query.where('loc').near({ center: [10, 10] });
3044 *     query.where('loc').near({ center: [10, 10], maxDistance: 5 });
3045 *     query.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true });
3046 *     query.near('loc', { center: [10, 10], maxDistance: 5 });
3047 *
3048 * @method near
3049 * @memberOf Query
3050 * @param {String} [path]
3051 * @param {Object} val
3052 * @return {Query} this
3053 * @see $near http://docs.mongodb.org/manual/reference/operator/near/
3054 * @see $nearSphere http://docs.mongodb.org/manual/reference/operator/nearSphere/
3055 * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/
3056 * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
3057 * @api public
3058 */
3059
3060/*!
3061 * Overwriting mquery is needed to support a couple different near() forms found in older
3062 * versions of mongoose
3063 * near([1,1])
3064 * near(1,1)
3065 * near(field, [1,2])
3066 * near(field, 1, 2)
3067 * In addition to all of the normal forms supported by mquery
3068 */
3069
3070Query.prototype.near = function() {
3071  var params = [];
3072  var sphere = this._mongooseOptions.nearSphere;
3073
3074  // TODO refactor
3075
3076  if (arguments.length === 1) {
3077    if (Array.isArray(arguments[0])) {
3078      params.push({center: arguments[0], spherical: sphere});
3079    } else if (typeof arguments[0] === 'string') {
3080      // just passing a path
3081      params.push(arguments[0]);
3082    } else if (utils.isObject(arguments[0])) {
3083      if (typeof arguments[0].spherical !== 'boolean') {
3084        arguments[0].spherical = sphere;
3085      }
3086      params.push(arguments[0]);
3087    } else {
3088      throw new TypeError('invalid argument');
3089    }
3090  } else if (arguments.length === 2) {
3091    if (typeof arguments[0] === 'number' && typeof arguments[1] === 'number') {
3092      params.push({center: [arguments[0], arguments[1]], spherical: sphere});
3093    } else if (typeof arguments[0] === 'string' && Array.isArray(arguments[1])) {
3094      params.push(arguments[0]);
3095      params.push({center: arguments[1], spherical: sphere});
3096    } else if (typeof arguments[0] === 'string' && utils.isObject(arguments[1])) {
3097      params.push(arguments[0]);
3098      if (typeof arguments[1].spherical !== 'boolean') {
3099        arguments[1].spherical = sphere;
3100      }
3101      params.push(arguments[1]);
3102    } else {
3103      throw new TypeError('invalid argument');
3104    }
3105  } else if (arguments.length === 3) {
3106    if (typeof arguments[0] === 'string' && typeof arguments[1] === 'number'
3107        && typeof arguments[2] === 'number') {
3108      params.push(arguments[0]);
3109      params.push({center: [arguments[1], arguments[2]], spherical: sphere});
3110    } else {
3111      throw new TypeError('invalid argument');
3112    }
3113  } else {
3114    throw new TypeError('invalid argument');
3115  }
3116
3117  return Query.base.near.apply(this, params);
3118};
3119
3120/**
3121 * _DEPRECATED_ Specifies a `$nearSphere` condition
3122 *
3123 * ####Example
3124 *
3125 *     query.where('loc').nearSphere({ center: [10, 10], maxDistance: 5 });
3126 *
3127 * **Deprecated.** Use `query.near()` instead with the `spherical` option set to `true`.
3128 *
3129 * ####Example
3130 *
3131 *     query.where('loc').near({ center: [10, 10], spherical: true });
3132 *
3133 * @deprecated
3134 * @see near() #query_Query-near
3135 * @see $near http://docs.mongodb.org/manual/reference/operator/near/
3136 * @see $nearSphere http://docs.mongodb.org/manual/reference/operator/nearSphere/
3137 * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/
3138 */
3139
3140Query.prototype.nearSphere = function() {
3141  this._mongooseOptions.nearSphere = true;
3142  this.near.apply(this, arguments);
3143  return this;
3144};
3145
3146/**
3147 * Specifies a $polygon condition
3148 *
3149 * ####Example
3150 *
3151 *     query.where('loc').within().polygon([10,20], [13, 25], [7,15])
3152 *     query.polygon('loc', [10,20], [13, 25], [7,15])
3153 *
3154 * @method polygon
3155 * @memberOf Query
3156 * @param {String|Array} [path]
3157 * @param {Array|Object} [coordinatePairs...]
3158 * @return {Query} this
3159 * @see $polygon http://docs.mongodb.org/manual/reference/operator/polygon/
3160 * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
3161 * @api public
3162 */
3163
3164/**
3165 * Specifies a $box condition
3166 *
3167 * ####Example
3168 *
3169 *     var lowerLeft = [40.73083, -73.99756]
3170 *     var upperRight= [40.741404,  -73.988135]
3171 *
3172 *     query.where('loc').within().box(lowerLeft, upperRight)
3173 *     query.box({ ll : lowerLeft, ur : upperRight })
3174 *
3175 * @method box
3176 * @memberOf Query
3177 * @see $box http://docs.mongodb.org/manual/reference/operator/box/
3178 * @see within() Query#within #query_Query-within
3179 * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
3180 * @param {Object} val
3181 * @param [Array] Upper Right Coords
3182 * @return {Query} this
3183 * @api public
3184 */
3185
3186/*!
3187 * this is needed to support the mongoose syntax of:
3188 * box(field, { ll : [x,y], ur : [x2,y2] })
3189 * box({ ll : [x,y], ur : [x2,y2] })
3190 */
3191
3192Query.prototype.box = function(ll, ur) {
3193  if (!Array.isArray(ll) && utils.isObject(ll)) {
3194    ur = ll.ur;
3195    ll = ll.ll;
3196  }
3197  return Query.base.box.call(this, ll, ur);
3198};
3199
3200/**
3201 * Specifies a $center or $centerSphere condition.
3202 *
3203 * ####Example
3204 *
3205 *     var area = { center: [50, 50], radius: 10, unique: true }
3206 *     query.where('loc').within().circle(area)
3207 *     // alternatively
3208 *     query.circle('loc', area);
3209 *
3210 *     // spherical calculations
3211 *     var area = { center: [50, 50], radius: 10, unique: true, spherical: true }
3212 *     query.where('loc').within().circle(area)
3213 *     // alternatively
3214 *     query.circle('loc', area);
3215 *
3216 * New in 3.7.0
3217 *
3218 * @method circle
3219 * @memberOf Query
3220 * @param {String} [path]
3221 * @param {Object} area
3222 * @return {Query} this
3223 * @see $center http://docs.mongodb.org/manual/reference/operator/center/
3224 * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/
3225 * @see $geoWithin http://docs.mongodb.org/manual/reference/operator/geoWithin/
3226 * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
3227 * @api public
3228 */
3229
3230/**
3231 * _DEPRECATED_ Alias for [circle](#query_Query-circle)
3232 *
3233 * **Deprecated.** Use [circle](#query_Query-circle) instead.
3234 *
3235 * @deprecated
3236 * @method center
3237 * @memberOf Query
3238 * @api public
3239 */
3240
3241Query.prototype.center = Query.base.circle;
3242
3243/**
3244 * _DEPRECATED_ Specifies a $centerSphere condition
3245 *
3246 * **Deprecated.** Use [circle](#query_Query-circle) instead.
3247 *
3248 * ####Example
3249 *
3250 *     var area = { center: [50, 50], radius: 10 };
3251 *     query.where('loc').within().centerSphere(area);
3252 *
3253 * @deprecated
3254 * @param {String} [path]
3255 * @param {Object} val
3256 * @return {Query} this
3257 * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
3258 * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/
3259 * @api public
3260 */
3261
3262Query.prototype.centerSphere = function() {
3263  if (arguments[0] && arguments[0].constructor.name === 'Object') {
3264    arguments[0].spherical = true;
3265  }
3266
3267  if (arguments[1] && arguments[1].constructor.name === 'Object') {
3268    arguments[1].spherical = true;
3269  }
3270
3271  Query.base.circle.apply(this, arguments);
3272};
3273
3274/**
3275 * Determines if field selection has been made.
3276 *
3277 * @method selected
3278 * @memberOf Query
3279 * @return {Boolean}
3280 * @api public
3281 */
3282
3283/**
3284 * Determines if inclusive field selection has been made.
3285 *
3286 *     query.selectedInclusively() // false
3287 *     query.select('name')
3288 *     query.selectedInclusively() // true
3289 *
3290 * @method selectedInclusively
3291 * @memberOf Query
3292 * @return {Boolean}
3293 * @api public
3294 */
3295
3296/**
3297 * Determines if exclusive field selection has been made.
3298 *
3299 *     query.selectedExclusively() // false
3300 *     query.select('-name')
3301 *     query.selectedExclusively() // true
3302 *     query.selectedInclusively() // false
3303 *
3304 * @method selectedExclusively
3305 * @memberOf Query
3306 * @return {Boolean}
3307 * @api public
3308 */
3309
3310/*!
3311 * Export
3312 */
3313
3314module.exports = Query;