You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3314 lines
88 KiB

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