query.js 90 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417
  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, { retainKeyOrder: true });
  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. if (options && Array.isArray(options.populate)) {
  824. var populate = options.populate;
  825. delete options.populate;
  826. var _numPopulate = populate.length;
  827. for (var i = 0; i < _numPopulate; ++i) {
  828. this.populate(populate[i]);
  829. }
  830. }
  831. return Query.base.setOptions.call(this, options);
  832. };
  833. /**
  834. * Returns the current query conditions as a JSON object.
  835. *
  836. * ####Example:
  837. *
  838. * var query = new Query();
  839. * query.find({ a: 1 }).where('b').gt(2);
  840. * query.getQuery(); // { a: 1, b: { $gt: 2 } }
  841. *
  842. * @return {Object} current query conditions
  843. * @api public
  844. */
  845. Query.prototype.getQuery = function() {
  846. return this._conditions;
  847. };
  848. /**
  849. * Returns the current update operations as a JSON object.
  850. *
  851. * ####Example:
  852. *
  853. * var query = new Query();
  854. * query.update({}, { $set: { a: 5 } });
  855. * query.getUpdate(); // { $set: { a: 5 } }
  856. *
  857. * @return {Object} current update operations
  858. * @api public
  859. */
  860. Query.prototype.getUpdate = function() {
  861. return this._update;
  862. };
  863. /**
  864. * Returns fields selection for this query.
  865. *
  866. * @method _fieldsForExec
  867. * @return {Object}
  868. * @api private
  869. * @receiver Query
  870. */
  871. /**
  872. * Return an update document with corrected $set operations.
  873. *
  874. * @method _updateForExec
  875. * @api private
  876. * @receiver Query
  877. */
  878. Query.prototype._updateForExec = function() {
  879. var update = utils.clone(this._update, {
  880. retainKeyOrder: true,
  881. transform: false,
  882. depopulate: true
  883. });
  884. var ops = Object.keys(update);
  885. var i = ops.length;
  886. var ret = {};
  887. while (i--) {
  888. var op = ops[i];
  889. if (this.options.overwrite) {
  890. ret[op] = update[op];
  891. continue;
  892. }
  893. if ('$' !== op[0]) {
  894. // fix up $set sugar
  895. if (!ret.$set) {
  896. if (update.$set) {
  897. ret.$set = update.$set;
  898. } else {
  899. ret.$set = {};
  900. }
  901. }
  902. ret.$set[op] = update[op];
  903. ops.splice(i, 1);
  904. if (!~ops.indexOf('$set')) ops.push('$set');
  905. } else if ('$set' === op) {
  906. if (!ret.$set) {
  907. ret[op] = update[op];
  908. }
  909. } else {
  910. ret[op] = update[op];
  911. }
  912. }
  913. this._compiledUpdate = ret;
  914. return ret;
  915. };
  916. /**
  917. * Makes sure _path is set.
  918. *
  919. * @method _ensurePath
  920. * @param {String} method
  921. * @api private
  922. * @receiver Query
  923. */
  924. /**
  925. * Determines if `conds` can be merged using `mquery().merge()`
  926. *
  927. * @method canMerge
  928. * @memberOf Query
  929. * @param {Object} conds
  930. * @return {Boolean}
  931. * @api private
  932. */
  933. /**
  934. * Returns default options for this query.
  935. *
  936. * @param {Model} model
  937. * @api private
  938. */
  939. Query.prototype._optionsForExec = function(model) {
  940. var options = Query.base._optionsForExec.call(this);
  941. delete options.populate;
  942. delete options.retainKeyOrder;
  943. model = model || this.model;
  944. if (!model) {
  945. return options;
  946. }
  947. if (!('safe' in options) && model.schema.options.safe) {
  948. options.safe = model.schema.options.safe;
  949. }
  950. if (!('readPreference' in options) && model.schema.options.read) {
  951. options.readPreference = model.schema.options.read;
  952. }
  953. return options;
  954. };
  955. /**
  956. * Sets the lean option.
  957. *
  958. * 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.
  959. *
  960. * ####Example:
  961. *
  962. * new Query().lean() // true
  963. * new Query().lean(true)
  964. * new Query().lean(false)
  965. *
  966. * Model.find().lean().exec(function (err, docs) {
  967. * docs[0] instanceof mongoose.Document // false
  968. * });
  969. *
  970. * 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).
  971. *
  972. * @param {Boolean} bool defaults to true
  973. * @return {Query} this
  974. * @api public
  975. */
  976. Query.prototype.lean = function(v) {
  977. this._mongooseOptions.lean = arguments.length ? !!v : true;
  978. return this;
  979. };
  980. /**
  981. * Thunk around find()
  982. *
  983. * @param {Function} [callback]
  984. * @return {Query} this
  985. * @api private
  986. */
  987. Query.prototype._find = function(callback) {
  988. if (this._castError) {
  989. callback(this._castError);
  990. return this;
  991. }
  992. this._applyPaths();
  993. this._fields = this._castFields(this._fields);
  994. var fields = this._fieldsForExec();
  995. var options = this._mongooseOptions;
  996. var _this = this;
  997. var cb = function(err, docs) {
  998. if (err) {
  999. return callback(err);
  1000. }
  1001. if (docs.length === 0) {
  1002. return callback(null, docs);
  1003. }
  1004. if (!options.populate) {
  1005. return options.lean === true
  1006. ? callback(null, docs)
  1007. : completeMany(_this.model, docs, fields, _this, null, callback);
  1008. }
  1009. var pop = helpers.preparePopulationOptionsMQ(_this, options);
  1010. pop.__noPromise = true;
  1011. _this.model.populate(docs, pop, function(err, docs) {
  1012. if (err) return callback(err);
  1013. return options.lean === true
  1014. ? callback(null, docs)
  1015. : completeMany(_this.model, docs, fields, _this, pop, callback);
  1016. });
  1017. };
  1018. return Query.base.find.call(this, {}, cb);
  1019. };
  1020. /**
  1021. * Finds documents.
  1022. *
  1023. * When no `callback` is passed, the query is not executed. When the query is executed, the result will be an array of documents.
  1024. *
  1025. * ####Example
  1026. *
  1027. * query.find({ name: 'Los Pollos Hermanos' }).find(callback)
  1028. *
  1029. * @param {Object} [criteria] mongodb selector
  1030. * @param {Function} [callback]
  1031. * @return {Query} this
  1032. * @api public
  1033. */
  1034. Query.prototype.find = function(conditions, callback) {
  1035. if (typeof conditions === 'function') {
  1036. callback = conditions;
  1037. conditions = {};
  1038. }
  1039. conditions = utils.toObject(conditions);
  1040. if (mquery.canMerge(conditions)) {
  1041. this.merge(conditions);
  1042. }
  1043. prepareDiscriminatorCriteria(this);
  1044. try {
  1045. this.cast(this.model);
  1046. this._castError = null;
  1047. } catch (err) {
  1048. this._castError = err;
  1049. }
  1050. // if we don't have a callback, then just return the query object
  1051. if (!callback) {
  1052. return Query.base.find.call(this);
  1053. }
  1054. this._find(callback);
  1055. return this;
  1056. };
  1057. /**
  1058. * Merges another Query or conditions object into this one.
  1059. *
  1060. * When a Query is passed, conditions, field selection and options are merged.
  1061. *
  1062. * @param {Query|Object} source
  1063. * @return {Query} this
  1064. */
  1065. Query.prototype.merge = function(source) {
  1066. if (!source) {
  1067. return this;
  1068. }
  1069. var opts = { retainKeyOrder: this.options.retainKeyOrder, overwrite: true };
  1070. if (source instanceof Query) {
  1071. // if source has a feature, apply it to ourselves
  1072. if (source._conditions) {
  1073. utils.merge(this._conditions, source._conditions, opts);
  1074. }
  1075. if (source._fields) {
  1076. this._fields || (this._fields = {});
  1077. utils.merge(this._fields, source._fields, opts);
  1078. }
  1079. if (source.options) {
  1080. this.options || (this.options = {});
  1081. utils.merge(this.options, source.options, opts);
  1082. }
  1083. if (source._update) {
  1084. this._update || (this._update = {});
  1085. utils.mergeClone(this._update, source._update);
  1086. }
  1087. if (source._distinct) {
  1088. this._distinct = source._distinct;
  1089. }
  1090. return this;
  1091. }
  1092. // plain object
  1093. utils.merge(this._conditions, source, opts);
  1094. return this;
  1095. };
  1096. /*!
  1097. * hydrates many documents
  1098. *
  1099. * @param {Model} model
  1100. * @param {Array} docs
  1101. * @param {Object} fields
  1102. * @param {Query} self
  1103. * @param {Array} [pop] array of paths used in population
  1104. * @param {Function} callback
  1105. */
  1106. function completeMany(model, docs, fields, self, pop, callback) {
  1107. var arr = [];
  1108. var count = docs.length;
  1109. var len = count;
  1110. var opts = pop ?
  1111. {populated: pop}
  1112. : undefined;
  1113. function init(err) {
  1114. if (err) return callback(err);
  1115. --count || callback(null, arr);
  1116. }
  1117. for (var i = 0; i < len; ++i) {
  1118. arr[i] = helpers.createModel(model, docs[i], fields);
  1119. arr[i].init(docs[i], opts, init);
  1120. }
  1121. }
  1122. /**
  1123. * Thunk around findOne()
  1124. *
  1125. * @param {Function} [callback]
  1126. * @see findOne http://docs.mongodb.org/manual/reference/method/db.collection.findOne/
  1127. * @api private
  1128. */
  1129. Query.prototype._findOne = function(callback) {
  1130. if (this._castError) {
  1131. return callback(this._castError);
  1132. }
  1133. this._applyPaths();
  1134. this._fields = this._castFields(this._fields);
  1135. var options = this._mongooseOptions;
  1136. var projection = this._fieldsForExec();
  1137. var _this = this;
  1138. // don't pass in the conditions because we already merged them in
  1139. Query.base.findOne.call(_this, {}, function(err, doc) {
  1140. if (err) {
  1141. return callback(err);
  1142. }
  1143. if (!doc) {
  1144. return callback(null, null);
  1145. }
  1146. if (!options.populate) {
  1147. return options.lean === true
  1148. ? callback(null, doc)
  1149. : completeOne(_this.model, doc, null, projection, _this, null, callback);
  1150. }
  1151. var pop = helpers.preparePopulationOptionsMQ(_this, options);
  1152. pop.__noPromise = true;
  1153. _this.model.populate(doc, pop, function(err, doc) {
  1154. if (err) {
  1155. return callback(err);
  1156. }
  1157. return options.lean === true
  1158. ? callback(null, doc)
  1159. : completeOne(_this.model, doc, null, projection, _this, pop, callback);
  1160. });
  1161. });
  1162. };
  1163. /**
  1164. * Declares the query a findOne operation. When executed, the first found document is passed to the callback.
  1165. *
  1166. * Passing a `callback` executes the query. The result of the query is a single document.
  1167. *
  1168. * * *Note:* `conditions` is optional, and if `conditions` is null or undefined,
  1169. * mongoose will send an empty `findOne` command to MongoDB, which will return
  1170. * an arbitrary document. If you're querying by `_id`, use `Model.findById()`
  1171. * instead.
  1172. *
  1173. * ####Example
  1174. *
  1175. * var query = Kitten.where({ color: 'white' });
  1176. * query.findOne(function (err, kitten) {
  1177. * if (err) return handleError(err);
  1178. * if (kitten) {
  1179. * // doc may be null if no document matched
  1180. * }
  1181. * });
  1182. *
  1183. * @param {Object|Query} [criteria] mongodb selector
  1184. * @param {Object} [projection] optional fields to return
  1185. * @param {Function} [callback]
  1186. * @return {Query} this
  1187. * @see findOne http://docs.mongodb.org/manual/reference/method/db.collection.findOne/
  1188. * @see Query.select #query_Query-select
  1189. * @api public
  1190. */
  1191. Query.prototype.findOne = function(conditions, projection, options, callback) {
  1192. if (typeof conditions === 'function') {
  1193. callback = conditions;
  1194. conditions = null;
  1195. projection = null;
  1196. options = null;
  1197. } else if (typeof projection === 'function') {
  1198. callback = projection;
  1199. options = null;
  1200. projection = null;
  1201. } else if (typeof options === 'function') {
  1202. callback = options;
  1203. options = null;
  1204. }
  1205. // make sure we don't send in the whole Document to merge()
  1206. conditions = utils.toObject(conditions);
  1207. this.op = 'findOne';
  1208. if (options) {
  1209. this.setOptions(options);
  1210. }
  1211. if (projection) {
  1212. this.select(projection);
  1213. }
  1214. if (mquery.canMerge(conditions)) {
  1215. this.merge(conditions);
  1216. } else if (conditions != null) {
  1217. throw new Error('Invalid argument to findOne(): ' +
  1218. util.inspect(conditions));
  1219. }
  1220. prepareDiscriminatorCriteria(this);
  1221. try {
  1222. this.cast(this.model);
  1223. this._castError = null;
  1224. } catch (err) {
  1225. this._castError = err;
  1226. }
  1227. if (!callback) {
  1228. // already merged in the conditions, don't need to send them in.
  1229. return Query.base.findOne.call(this);
  1230. }
  1231. this._findOne(callback);
  1232. return this;
  1233. };
  1234. /**
  1235. * Thunk around count()
  1236. *
  1237. * @param {Function} [callback]
  1238. * @see count http://docs.mongodb.org/manual/reference/method/db.collection.count/
  1239. * @api private
  1240. */
  1241. Query.prototype._count = function(callback) {
  1242. try {
  1243. this.cast(this.model);
  1244. } catch (err) {
  1245. process.nextTick(function() {
  1246. callback(err);
  1247. });
  1248. return this;
  1249. }
  1250. var conds = this._conditions;
  1251. var options = this._optionsForExec();
  1252. this._collection.count(conds, options, utils.tick(callback));
  1253. };
  1254. /**
  1255. * Specifying this query as a `count` query.
  1256. *
  1257. * Passing a `callback` executes the query.
  1258. *
  1259. * ####Example:
  1260. *
  1261. * var countQuery = model.where({ 'color': 'black' }).count();
  1262. *
  1263. * query.count({ color: 'black' }).count(callback)
  1264. *
  1265. * query.count({ color: 'black' }, callback)
  1266. *
  1267. * query.where('color', 'black').count(function (err, count) {
  1268. * if (err) return handleError(err);
  1269. * console.log('there are %d kittens', count);
  1270. * })
  1271. *
  1272. * @param {Object} [criteria] mongodb selector
  1273. * @param {Function} [callback]
  1274. * @return {Query} this
  1275. * @see count http://docs.mongodb.org/manual/reference/method/db.collection.count/
  1276. * @api public
  1277. */
  1278. Query.prototype.count = function(conditions, callback) {
  1279. if (typeof conditions === 'function') {
  1280. callback = conditions;
  1281. conditions = undefined;
  1282. }
  1283. if (mquery.canMerge(conditions)) {
  1284. this.merge(conditions);
  1285. }
  1286. this.op = 'count';
  1287. if (!callback) {
  1288. return this;
  1289. }
  1290. this._count(callback);
  1291. return this;
  1292. };
  1293. /**
  1294. * Declares or executes a distict() operation.
  1295. *
  1296. * Passing a `callback` executes the query.
  1297. *
  1298. * ####Example
  1299. *
  1300. * distinct(field, conditions, callback)
  1301. * distinct(field, conditions)
  1302. * distinct(field, callback)
  1303. * distinct(field)
  1304. * distinct(callback)
  1305. * distinct()
  1306. *
  1307. * @param {String} [field]
  1308. * @param {Object|Query} [criteria]
  1309. * @param {Function} [callback]
  1310. * @return {Query} this
  1311. * @see distinct http://docs.mongodb.org/manual/reference/method/db.collection.distinct/
  1312. * @api public
  1313. */
  1314. Query.prototype.distinct = function(field, conditions, callback) {
  1315. if (!callback) {
  1316. if (typeof conditions === 'function') {
  1317. callback = conditions;
  1318. conditions = undefined;
  1319. } else if (typeof field === 'function') {
  1320. callback = field;
  1321. field = undefined;
  1322. conditions = undefined;
  1323. }
  1324. }
  1325. conditions = utils.toObject(conditions);
  1326. if (mquery.canMerge(conditions)) {
  1327. this.merge(conditions);
  1328. }
  1329. try {
  1330. this.cast(this.model);
  1331. } catch (err) {
  1332. if (!callback) {
  1333. throw err;
  1334. }
  1335. callback(err);
  1336. return this;
  1337. }
  1338. return Query.base.distinct.call(this, {}, field, callback);
  1339. };
  1340. /**
  1341. * Sets the sort order
  1342. *
  1343. * If an object is passed, values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`.
  1344. *
  1345. * If a string is passed, it must be a space delimited list of path names. The
  1346. * sort order of each path is ascending unless the path name is prefixed with `-`
  1347. * which will be treated as descending.
  1348. *
  1349. * ####Example
  1350. *
  1351. * // sort by "field" ascending and "test" descending
  1352. * query.sort({ field: 'asc', test: -1 });
  1353. *
  1354. * // equivalent
  1355. * query.sort('field -test');
  1356. *
  1357. * ####Note
  1358. *
  1359. * Cannot be used with `distinct()`
  1360. *
  1361. * @param {Object|String} arg
  1362. * @return {Query} this
  1363. * @see cursor.sort http://docs.mongodb.org/manual/reference/method/cursor.sort/
  1364. * @api public
  1365. */
  1366. Query.prototype.sort = function(arg) {
  1367. var nArg = {};
  1368. if (arguments.length > 1) {
  1369. throw new Error('sort() only takes 1 Argument');
  1370. }
  1371. if (Array.isArray(arg)) {
  1372. // time to deal with the terrible syntax
  1373. for (var i = 0; i < arg.length; i++) {
  1374. if (!Array.isArray(arg[i])) throw new Error('Invalid sort() argument.');
  1375. nArg[arg[i][0]] = arg[i][1];
  1376. }
  1377. } else {
  1378. nArg = arg;
  1379. }
  1380. return Query.base.sort.call(this, nArg);
  1381. };
  1382. /**
  1383. * Declare and/or execute this query as a remove() operation.
  1384. *
  1385. * ####Example
  1386. *
  1387. * Model.remove({ artist: 'Anne Murray' }, callback)
  1388. *
  1389. * ####Note
  1390. *
  1391. * 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.
  1392. *
  1393. * // not executed
  1394. * var query = Model.find().remove({ name: 'Anne Murray' })
  1395. *
  1396. * // executed
  1397. * query.remove({ name: 'Anne Murray' }, callback)
  1398. * query.remove({ name: 'Anne Murray' }).remove(callback)
  1399. *
  1400. * // executed without a callback
  1401. * query.exec()
  1402. *
  1403. * // summary
  1404. * query.remove(conds, fn); // executes
  1405. * query.remove(conds)
  1406. * query.remove(fn) // executes
  1407. * query.remove()
  1408. *
  1409. * @param {Object|Query} [criteria] mongodb selector
  1410. * @param {Function} [callback]
  1411. * @return {Query} this
  1412. * @see remove http://docs.mongodb.org/manual/reference/method/db.collection.remove/
  1413. * @api public
  1414. */
  1415. Query.prototype.remove = function(cond, callback) {
  1416. if (typeof cond === 'function') {
  1417. callback = cond;
  1418. cond = null;
  1419. }
  1420. var cb = typeof callback === 'function';
  1421. try {
  1422. this.cast(this.model);
  1423. } catch (err) {
  1424. if (cb) return process.nextTick(callback.bind(null, err));
  1425. return this;
  1426. }
  1427. return Query.base.remove.call(this, cond, callback);
  1428. };
  1429. /*!
  1430. * hydrates a document
  1431. *
  1432. * @param {Model} model
  1433. * @param {Document} doc
  1434. * @param {Object} res 3rd parameter to callback
  1435. * @param {Object} fields
  1436. * @param {Query} self
  1437. * @param {Array} [pop] array of paths used in population
  1438. * @param {Function} callback
  1439. */
  1440. function completeOne(model, doc, res, fields, self, pop, callback) {
  1441. var opts = pop ?
  1442. {populated: pop}
  1443. : undefined;
  1444. var casted = helpers.createModel(model, doc, fields);
  1445. casted.init(doc, opts, function(err) {
  1446. if (err) {
  1447. return callback(err);
  1448. }
  1449. if (res) {
  1450. return callback(null, casted, res);
  1451. }
  1452. callback(null, casted);
  1453. });
  1454. }
  1455. /*!
  1456. * If the model is a discriminator type and not root, then add the key & value to the criteria.
  1457. */
  1458. function prepareDiscriminatorCriteria(query) {
  1459. if (!query || !query.model || !query.model.schema) {
  1460. return;
  1461. }
  1462. var schema = query.model.schema;
  1463. if (schema && schema.discriminatorMapping && !schema.discriminatorMapping.isRoot) {
  1464. query._conditions[schema.discriminatorMapping.key] = schema.discriminatorMapping.value;
  1465. }
  1466. }
  1467. /**
  1468. * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) update command.
  1469. *
  1470. * 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.
  1471. *
  1472. * ####Available options
  1473. *
  1474. * - `new`: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0)
  1475. * - `upsert`: bool - creates the object if it doesn't exist. defaults to false.
  1476. * - `fields`: {Object|String} - Field selection. Equivalent to `.select(fields).findOneAndUpdate()`
  1477. * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  1478. * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
  1479. * - `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.
  1480. * - `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/).
  1481. * - `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)
  1482. * - `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.
  1483. *
  1484. * ####Callback Signature
  1485. * function(error, doc) {
  1486. * // error: any errors that occurred
  1487. * // doc: the document before updates are applied if `new: false`, or after updates if `new = true`
  1488. * }
  1489. *
  1490. * ####Examples
  1491. *
  1492. * query.findOneAndUpdate(conditions, update, options, callback) // executes
  1493. * query.findOneAndUpdate(conditions, update, options) // returns Query
  1494. * query.findOneAndUpdate(conditions, update, callback) // executes
  1495. * query.findOneAndUpdate(conditions, update) // returns Query
  1496. * query.findOneAndUpdate(update, callback) // returns Query
  1497. * query.findOneAndUpdate(update) // returns Query
  1498. * query.findOneAndUpdate(callback) // executes
  1499. * query.findOneAndUpdate() // returns Query
  1500. *
  1501. * @method findOneAndUpdate
  1502. * @memberOf Query
  1503. * @param {Object|Query} [query]
  1504. * @param {Object} [doc]
  1505. * @param {Object} [options]
  1506. * @param {Function} [callback]
  1507. * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command
  1508. * @return {Query} this
  1509. * @api public
  1510. */
  1511. Query.prototype.findOneAndUpdate = function(criteria, doc, options, callback) {
  1512. this.op = 'findOneAndUpdate';
  1513. this._validate();
  1514. switch (arguments.length) {
  1515. case 3:
  1516. if (typeof options === 'function') {
  1517. callback = options;
  1518. options = {};
  1519. }
  1520. break;
  1521. case 2:
  1522. if (typeof doc === 'function') {
  1523. callback = doc;
  1524. doc = criteria;
  1525. criteria = undefined;
  1526. }
  1527. options = undefined;
  1528. break;
  1529. case 1:
  1530. if (typeof criteria === 'function') {
  1531. callback = criteria;
  1532. criteria = options = doc = undefined;
  1533. } else {
  1534. doc = criteria;
  1535. criteria = options = undefined;
  1536. }
  1537. }
  1538. if (mquery.canMerge(criteria)) {
  1539. this.merge(criteria);
  1540. }
  1541. // apply doc
  1542. if (doc) {
  1543. this._mergeUpdate(doc);
  1544. }
  1545. if (options) {
  1546. options = utils.clone(options, { retainKeyOrder: true });
  1547. if (options.projection) {
  1548. this.select(options.projection);
  1549. delete options.projection;
  1550. }
  1551. if (options.fields) {
  1552. this.select(options.fields);
  1553. delete options.fields;
  1554. }
  1555. this.setOptions(options);
  1556. }
  1557. if (!callback) {
  1558. return this;
  1559. }
  1560. return this._findOneAndUpdate(callback);
  1561. };
  1562. /**
  1563. * Thunk around findOneAndUpdate()
  1564. *
  1565. * @param {Function} [callback]
  1566. * @api private
  1567. */
  1568. Query.prototype._findOneAndUpdate = function(callback) {
  1569. this._findAndModify('update', callback);
  1570. return this;
  1571. };
  1572. /**
  1573. * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) remove command.
  1574. *
  1575. * Finds a matching document, removes it, passing the found document (if any) to the callback. Executes immediately if `callback` is passed.
  1576. *
  1577. * ####Available options
  1578. *
  1579. * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  1580. * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
  1581. * - `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)
  1582. *
  1583. * ####Callback Signature
  1584. * function(error, doc, result) {
  1585. * // error: any errors that occurred
  1586. * // doc: the document before updates are applied if `new: false`, or after updates if `new = true`
  1587. * // result: [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
  1588. * }
  1589. *
  1590. * ####Examples
  1591. *
  1592. * A.where().findOneAndRemove(conditions, options, callback) // executes
  1593. * A.where().findOneAndRemove(conditions, options) // return Query
  1594. * A.where().findOneAndRemove(conditions, callback) // executes
  1595. * A.where().findOneAndRemove(conditions) // returns Query
  1596. * A.where().findOneAndRemove(callback) // executes
  1597. * A.where().findOneAndRemove() // returns Query
  1598. *
  1599. * @method findOneAndRemove
  1600. * @memberOf Query
  1601. * @param {Object} [conditions]
  1602. * @param {Object} [options]
  1603. * @param {Function} [callback]
  1604. * @return {Query} this
  1605. * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command
  1606. * @api public
  1607. */
  1608. Query.prototype.findOneAndRemove = function(conditions, options, callback) {
  1609. this.op = 'findOneAndRemove';
  1610. this._validate();
  1611. switch (arguments.length) {
  1612. case 2:
  1613. if (typeof options === 'function') {
  1614. callback = options;
  1615. options = {};
  1616. }
  1617. break;
  1618. case 1:
  1619. if (typeof conditions === 'function') {
  1620. callback = conditions;
  1621. conditions = undefined;
  1622. options = undefined;
  1623. }
  1624. break;
  1625. }
  1626. if (mquery.canMerge(conditions)) {
  1627. this.merge(conditions);
  1628. }
  1629. options && this.setOptions(options);
  1630. if (!callback) {
  1631. return this;
  1632. }
  1633. this._findOneAndRemove(callback);
  1634. return this;
  1635. };
  1636. /**
  1637. * Thunk around findOneAndRemove()
  1638. *
  1639. * @param {Function} [callback]
  1640. * @return {Query} this
  1641. * @api private
  1642. */
  1643. Query.prototype._findOneAndRemove = function(callback) {
  1644. Query.base.findOneAndRemove.call(this, callback);
  1645. };
  1646. /**
  1647. * Override mquery.prototype._findAndModify to provide casting etc.
  1648. *
  1649. * @param {String} type - either "remove" or "update"
  1650. * @param {Function} callback
  1651. * @api private
  1652. */
  1653. Query.prototype._findAndModify = function(type, callback) {
  1654. if (typeof callback !== 'function') {
  1655. throw new Error('Expected callback in _findAndModify');
  1656. }
  1657. var model = this.model;
  1658. var schema = model.schema;
  1659. var _this = this;
  1660. var castedQuery;
  1661. var castedDoc;
  1662. var fields;
  1663. var opts;
  1664. var doValidate;
  1665. castedQuery = castQuery(this);
  1666. if (castedQuery instanceof Error) {
  1667. return callback(castedQuery);
  1668. }
  1669. opts = this._optionsForExec(model);
  1670. if ('strict' in opts) {
  1671. this._mongooseOptions.strict = opts.strict;
  1672. }
  1673. if (type === 'remove') {
  1674. opts.remove = true;
  1675. } else {
  1676. if (!('new' in opts)) {
  1677. opts.new = false;
  1678. }
  1679. if (!('upsert' in opts)) {
  1680. opts.upsert = false;
  1681. }
  1682. if (opts.upsert || opts['new']) {
  1683. opts.remove = false;
  1684. }
  1685. castedDoc = castDoc(this, opts.overwrite);
  1686. castedDoc = setDefaultsOnInsert(this, schema, castedDoc, opts);
  1687. if (!castedDoc) {
  1688. if (opts.upsert) {
  1689. // still need to do the upsert to empty doc
  1690. var doc = utils.clone(castedQuery);
  1691. delete doc._id;
  1692. castedDoc = {$set: doc};
  1693. } else {
  1694. return this.findOne(callback);
  1695. }
  1696. } else if (castedDoc instanceof Error) {
  1697. return callback(castedDoc);
  1698. } else {
  1699. // In order to make MongoDB 2.6 happy (see
  1700. // https://jira.mongodb.org/browse/SERVER-12266 and related issues)
  1701. // if we have an actual update document but $set is empty, junk the $set.
  1702. if (castedDoc.$set && Object.keys(castedDoc.$set).length === 0) {
  1703. delete castedDoc.$set;
  1704. }
  1705. }
  1706. doValidate = updateValidators(this, schema, castedDoc, opts);
  1707. }
  1708. this._applyPaths();
  1709. var options = this._mongooseOptions;
  1710. if (this._fields) {
  1711. fields = utils.clone(this._fields);
  1712. opts.fields = this._castFields(fields);
  1713. if (opts.fields instanceof Error) {
  1714. return callback(opts.fields);
  1715. }
  1716. }
  1717. if (opts.sort) convertSortToArray(opts);
  1718. var cb = function(err, doc, res) {
  1719. if (err) {
  1720. return callback(err);
  1721. }
  1722. if (!doc || (utils.isObject(doc) && Object.keys(doc).length === 0)) {
  1723. if (opts.passRawResult) {
  1724. return callback(null, null, res);
  1725. }
  1726. return callback(null, null);
  1727. }
  1728. if (!opts.passRawResult) {
  1729. res = null;
  1730. }
  1731. if (!options.populate) {
  1732. return options.lean === true
  1733. ? (opts.passRawResult ? callback(null, doc, res) : callback(null, doc))
  1734. : completeOne(_this.model, doc, res, fields, _this, null, callback);
  1735. }
  1736. var pop = helpers.preparePopulationOptionsMQ(_this, options);
  1737. pop.__noPromise = true;
  1738. _this.model.populate(doc, pop, function(err, doc) {
  1739. if (err) {
  1740. return callback(err);
  1741. }
  1742. return options.lean === true
  1743. ? (opts.passRawResult ? callback(null, doc, res) : callback(null, doc))
  1744. : completeOne(_this.model, doc, res, fields, _this, pop, callback);
  1745. });
  1746. };
  1747. if (opts.runValidators && doValidate) {
  1748. var _callback = function(error) {
  1749. if (error) {
  1750. return callback(error);
  1751. }
  1752. _this._collection.findAndModify(castedQuery, castedDoc, opts, utils.tick(function(error, res) {
  1753. return cb(error, res ? res.value : res, res);
  1754. }));
  1755. };
  1756. try {
  1757. doValidate(_callback);
  1758. } catch (error) {
  1759. callback(error);
  1760. }
  1761. } else {
  1762. this._collection.findAndModify(castedQuery, castedDoc, opts, utils.tick(function(error, res) {
  1763. return cb(error, res ? res.value : res, res);
  1764. }));
  1765. }
  1766. return this;
  1767. };
  1768. /**
  1769. * Override mquery.prototype._mergeUpdate to handle mongoose objects in
  1770. * updates.
  1771. *
  1772. * @param {Object} doc
  1773. * @api private
  1774. */
  1775. Query.prototype._mergeUpdate = function(doc) {
  1776. if (!this._update) this._update = {};
  1777. if (doc instanceof Query) {
  1778. if (doc._update) {
  1779. utils.mergeClone(this._update, doc._update);
  1780. }
  1781. } else {
  1782. utils.mergeClone(this._update, doc);
  1783. }
  1784. };
  1785. /*!
  1786. * The mongodb driver 1.3.23 only supports the nested array sort
  1787. * syntax. We must convert it or sorting findAndModify will not work.
  1788. */
  1789. function convertSortToArray(opts) {
  1790. if (Array.isArray(opts.sort)) {
  1791. return;
  1792. }
  1793. if (!utils.isObject(opts.sort)) {
  1794. return;
  1795. }
  1796. var sort = [];
  1797. for (var key in opts.sort) {
  1798. if (utils.object.hasOwnProperty(opts.sort, key)) {
  1799. sort.push([key, opts.sort[key]]);
  1800. }
  1801. }
  1802. opts.sort = sort;
  1803. }
  1804. /**
  1805. * Internal thunk for .update()
  1806. *
  1807. * @param {Function} callback
  1808. * @see Model.update #model_Model.update
  1809. * @api private
  1810. */
  1811. Query.prototype._execUpdate = function(callback) {
  1812. var schema = this.model.schema;
  1813. var doValidate;
  1814. var _this;
  1815. var castedQuery = this._conditions;
  1816. var castedDoc = this._update;
  1817. var options = this.options;
  1818. if (this._castError) {
  1819. callback(this._castError);
  1820. return this;
  1821. }
  1822. if (this.options.runValidators) {
  1823. _this = this;
  1824. doValidate = updateValidators(this, schema, castedDoc, options);
  1825. var _callback = function(err) {
  1826. if (err) {
  1827. return callback(err);
  1828. }
  1829. Query.base.update.call(_this, castedQuery, castedDoc, options, callback);
  1830. };
  1831. try {
  1832. doValidate(_callback);
  1833. } catch (err) {
  1834. process.nextTick(function() {
  1835. callback(err);
  1836. });
  1837. }
  1838. return this;
  1839. }
  1840. Query.base.update.call(this, castedQuery, castedDoc, options, callback);
  1841. return this;
  1842. };
  1843. /**
  1844. * Declare and/or execute this query as an update() operation.
  1845. *
  1846. * _All paths passed that are not $atomic operations will become $set ops._
  1847. *
  1848. * ####Example
  1849. *
  1850. * Model.where({ _id: id }).update({ title: 'words' })
  1851. *
  1852. * // becomes
  1853. *
  1854. * Model.where({ _id: id }).update({ $set: { title: 'words' }})
  1855. *
  1856. * ####Valid options:
  1857. *
  1858. * - `safe` (boolean) safe mode (defaults to value set in schema (true))
  1859. * - `upsert` (boolean) whether to create the doc if it doesn't match (false)
  1860. * - `multi` (boolean) whether multiple documents should be updated (false)
  1861. * - `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.
  1862. * - `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/).
  1863. * - `strict` (boolean) overrides the `strict` option for this update
  1864. * - `overwrite` (boolean) disables update-only mode, allowing you to overwrite the doc (false)
  1865. * - `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.
  1866. *
  1867. * ####Note
  1868. *
  1869. * 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.
  1870. *
  1871. * ####Note
  1872. *
  1873. * 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.
  1874. *
  1875. * var q = Model.where({ _id: id });
  1876. * q.update({ $set: { name: 'bob' }}).update(); // not executed
  1877. *
  1878. * q.update({ $set: { name: 'bob' }}).exec(); // executed
  1879. *
  1880. * // keys that are not $atomic ops become $set.
  1881. * // this executes the same command as the previous example.
  1882. * q.update({ name: 'bob' }).exec();
  1883. *
  1884. * // overwriting with empty docs
  1885. * var q = Model.where({ _id: id }).setOptions({ overwrite: true })
  1886. * q.update({ }, callback); // executes
  1887. *
  1888. * // multi update with overwrite to empty doc
  1889. * var q = Model.where({ _id: id });
  1890. * q.setOptions({ multi: true, overwrite: true })
  1891. * q.update({ });
  1892. * q.update(callback); // executed
  1893. *
  1894. * // multi updates
  1895. * Model.where()
  1896. * .update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, callback)
  1897. *
  1898. * // more multi updates
  1899. * Model.where()
  1900. * .setOptions({ multi: true })
  1901. * .update({ $set: { arr: [] }}, callback)
  1902. *
  1903. * // single update by default
  1904. * Model.where({ email: 'address@example.com' })
  1905. * .update({ $inc: { counter: 1 }}, callback)
  1906. *
  1907. * API summary
  1908. *
  1909. * update(criteria, doc, options, cb) // executes
  1910. * update(criteria, doc, options)
  1911. * update(criteria, doc, cb) // executes
  1912. * update(criteria, doc)
  1913. * update(doc, cb) // executes
  1914. * update(doc)
  1915. * update(cb) // executes
  1916. * update(true) // executes
  1917. * update()
  1918. *
  1919. * @param {Object} [criteria]
  1920. * @param {Object} [doc] the update command
  1921. * @param {Object} [options]
  1922. * @param {Function} [callback]
  1923. * @return {Query} this
  1924. * @see Model.update #model_Model.update
  1925. * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/
  1926. * @api public
  1927. */
  1928. Query.prototype.update = function(conditions, doc, options, callback) {
  1929. if (typeof options === 'function') {
  1930. // .update(conditions, doc, callback)
  1931. callback = options;
  1932. options = null;
  1933. } else if (typeof doc === 'function') {
  1934. // .update(doc, callback);
  1935. callback = doc;
  1936. doc = conditions;
  1937. conditions = {};
  1938. options = null;
  1939. } else if (typeof conditions === 'function') {
  1940. // .update(callback)
  1941. callback = conditions;
  1942. conditions = undefined;
  1943. doc = undefined;
  1944. options = undefined;
  1945. } else if (typeof conditions === 'object' && !doc && !options && !callback) {
  1946. // .update(doc)
  1947. doc = conditions;
  1948. conditions = undefined;
  1949. options = undefined;
  1950. callback = undefined;
  1951. }
  1952. // make sure we don't send in the whole Document to merge()
  1953. conditions = utils.toObject(conditions);
  1954. var oldCb = callback;
  1955. if (oldCb) {
  1956. if (typeof oldCb === 'function') {
  1957. callback = function(error, result) {
  1958. oldCb(error, result ? result.result : {ok: 0, n: 0, nModified: 0});
  1959. };
  1960. } else {
  1961. throw new Error('Invalid callback() argument.');
  1962. }
  1963. }
  1964. // strict is an option used in the update checking, make sure it gets set
  1965. if (options) {
  1966. if ('strict' in options) {
  1967. this._mongooseOptions.strict = options.strict;
  1968. }
  1969. }
  1970. // if doc is undefined at this point, this means this function is being
  1971. // executed by exec(not always see below). Grab the update doc from here in
  1972. // order to validate
  1973. // This could also be somebody calling update() or update({}). Probably not a
  1974. // common use case, check for _update to make sure we don't do anything bad
  1975. if (!doc && this._update) {
  1976. doc = this._updateForExec();
  1977. }
  1978. if (mquery.canMerge(conditions)) {
  1979. this.merge(conditions);
  1980. }
  1981. // validate the selector part of the query
  1982. var castedQuery = castQuery(this);
  1983. if (castedQuery instanceof Error) {
  1984. this._castError = castedQuery;
  1985. if (callback) {
  1986. callback(castedQuery);
  1987. return this;
  1988. } else if (!options || !options.dontThrowCastError) {
  1989. throw castedQuery;
  1990. }
  1991. }
  1992. // validate the update part of the query
  1993. var castedDoc;
  1994. try {
  1995. var $options = {retainKeyOrder: true};
  1996. if (options && options.minimize) {
  1997. $options.minimize = true;
  1998. }
  1999. castedDoc = this._castUpdate(utils.clone(doc, $options),
  2000. options && options.overwrite);
  2001. } catch (err) {
  2002. this._castError = castedQuery;
  2003. if (callback) {
  2004. callback(err);
  2005. return this;
  2006. } else if (!options || !options.dontThrowCastError) {
  2007. throw err;
  2008. }
  2009. }
  2010. castedDoc = setDefaultsOnInsert(this, this.schema, castedDoc, options);
  2011. if (!castedDoc) {
  2012. // Make sure promises know that this is still an update, see gh-2796
  2013. this.op = 'update';
  2014. callback && callback(null);
  2015. return this;
  2016. }
  2017. if (utils.isObject(options)) {
  2018. this.setOptions(options);
  2019. }
  2020. if (!this._update) this._update = castedDoc;
  2021. // Hooks
  2022. if (callback) {
  2023. return this._execUpdate(callback);
  2024. }
  2025. return Query.base.update.call(this, castedQuery, castedDoc, options, callback);
  2026. };
  2027. /**
  2028. * Executes the query
  2029. *
  2030. * ####Examples:
  2031. *
  2032. * var promise = query.exec();
  2033. * var promise = query.exec('update');
  2034. *
  2035. * query.exec(callback);
  2036. * query.exec('find', callback);
  2037. *
  2038. * @param {String|Function} [operation]
  2039. * @param {Function} [callback]
  2040. * @return {Promise}
  2041. * @api public
  2042. */
  2043. Query.prototype.exec = function exec(op, callback) {
  2044. var Promise = PromiseProvider.get();
  2045. var _this = this;
  2046. if (typeof op === 'function') {
  2047. callback = op;
  2048. op = null;
  2049. } else if (typeof op === 'string') {
  2050. this.op = op;
  2051. }
  2052. var _results;
  2053. var promise = new Promise.ES6(function(resolve, reject) {
  2054. if (!_this.op) {
  2055. resolve();
  2056. return;
  2057. }
  2058. _this[_this.op].call(_this, function(error, res) {
  2059. if (error) {
  2060. reject(error);
  2061. return;
  2062. }
  2063. _results = arguments;
  2064. resolve(res);
  2065. });
  2066. });
  2067. if (callback) {
  2068. promise.then(
  2069. function() {
  2070. callback.apply(null, _results);
  2071. },
  2072. function(error) {
  2073. callback(error);
  2074. }).
  2075. catch(function(error) {
  2076. // If we made it here, we must have an error in the callback re:
  2077. // gh-4500, so we need to emit.
  2078. setImmediate(function() {
  2079. _this.model.emit('error', error);
  2080. });
  2081. });
  2082. }
  2083. return promise;
  2084. };
  2085. /**
  2086. * Executes the query returning a `Promise` which will be
  2087. * resolved with either the doc(s) or rejected with the error.
  2088. *
  2089. * @param {Function} [resolve]
  2090. * @param {Function} [reject]
  2091. * @return {Promise}
  2092. * @api public
  2093. */
  2094. Query.prototype.then = function(resolve, reject) {
  2095. return this.exec().then(resolve, reject);
  2096. };
  2097. /**
  2098. * Executes the query returning a `Promise` which will be
  2099. * resolved with either the doc(s) or rejected with the error.
  2100. * Like `.then()`, but only takes a rejection handler.
  2101. *
  2102. * @param {Function} [reject]
  2103. * @return {Promise}
  2104. * @api public
  2105. */
  2106. Query.prototype.catch = function(reject) {
  2107. return this.exec().then(null, reject);
  2108. };
  2109. /**
  2110. * Finds the schema for `path`. This is different than
  2111. * calling `schema.path` as it also resolves paths with
  2112. * positional selectors (something.$.another.$.path).
  2113. *
  2114. * @param {String} path
  2115. * @api private
  2116. */
  2117. Query.prototype._getSchema = function _getSchema(path) {
  2118. return this.model._getSchema(path);
  2119. };
  2120. /*!
  2121. * These operators require casting docs
  2122. * to real Documents for Update operations.
  2123. */
  2124. var castOps = {
  2125. $push: 1,
  2126. $pushAll: 1,
  2127. $addToSet: 1,
  2128. $set: 1
  2129. };
  2130. /*!
  2131. * These operators should be cast to numbers instead
  2132. * of their path schema type.
  2133. */
  2134. var numberOps = {
  2135. $pop: 1,
  2136. $unset: 1,
  2137. $inc: 1
  2138. };
  2139. /**
  2140. * Casts obj for an update command.
  2141. *
  2142. * @param {Object} obj
  2143. * @return {Object} obj after casting its values
  2144. * @api private
  2145. */
  2146. Query.prototype._castUpdate = function _castUpdate(obj, overwrite) {
  2147. if (!obj) {
  2148. return undefined;
  2149. }
  2150. var ops = Object.keys(obj);
  2151. var i = ops.length;
  2152. var ret = {};
  2153. var hasKeys;
  2154. var val;
  2155. var hasDollarKey = false;
  2156. while (i--) {
  2157. var op = ops[i];
  2158. // if overwrite is set, don't do any of the special $set stuff
  2159. if (op[0] !== '$' && !overwrite) {
  2160. // fix up $set sugar
  2161. if (!ret.$set) {
  2162. if (obj.$set) {
  2163. ret.$set = obj.$set;
  2164. } else {
  2165. ret.$set = {};
  2166. }
  2167. }
  2168. ret.$set[op] = obj[op];
  2169. ops.splice(i, 1);
  2170. if (!~ops.indexOf('$set')) ops.push('$set');
  2171. } else if (op === '$set') {
  2172. if (!ret.$set) {
  2173. ret[op] = obj[op];
  2174. }
  2175. } else {
  2176. ret[op] = obj[op];
  2177. }
  2178. }
  2179. // cast each value
  2180. i = ops.length;
  2181. // if we get passed {} for the update, we still need to respect that when it
  2182. // is an overwrite scenario
  2183. if (overwrite) {
  2184. hasKeys = true;
  2185. }
  2186. while (i--) {
  2187. op = ops[i];
  2188. val = ret[op];
  2189. hasDollarKey = hasDollarKey || op.charAt(0) === '$';
  2190. if (val &&
  2191. typeof val === 'object' &&
  2192. (!overwrite || hasDollarKey)) {
  2193. hasKeys |= this._walkUpdatePath(val, op);
  2194. } else if (overwrite && ret && typeof ret === 'object') {
  2195. // if we are just using overwrite, cast the query and then we will
  2196. // *always* return the value, even if it is an empty object. We need to
  2197. // set hasKeys above because we need to account for the case where the
  2198. // user passes {} and wants to clobber the whole document
  2199. // Also, _walkUpdatePath expects an operation, so give it $set since that
  2200. // is basically what we're doing
  2201. this._walkUpdatePath(ret, '$set');
  2202. } else {
  2203. var msg = 'Invalid atomic update value for ' + op + '. '
  2204. + 'Expected an object, received ' + typeof val;
  2205. throw new Error(msg);
  2206. }
  2207. }
  2208. return hasKeys && ret;
  2209. };
  2210. /**
  2211. * Walk each path of obj and cast its values
  2212. * according to its schema.
  2213. *
  2214. * @param {Object} obj - part of a query
  2215. * @param {String} op - the atomic operator ($pull, $set, etc)
  2216. * @param {String} pref - path prefix (internal only)
  2217. * @return {Bool} true if this path has keys to update
  2218. * @api private
  2219. */
  2220. Query.prototype._walkUpdatePath = function _walkUpdatePath(obj, op, pref) {
  2221. var prefix = pref ? pref + '.' : '',
  2222. keys = Object.keys(obj),
  2223. i = keys.length,
  2224. hasKeys = false,
  2225. schema,
  2226. key,
  2227. val;
  2228. var useNestedStrict = this.schema.options.useNestedStrict;
  2229. while (i--) {
  2230. key = keys[i];
  2231. val = obj[key];
  2232. if (val && val.constructor.name === 'Object') {
  2233. // watch for embedded doc schemas
  2234. schema = this._getSchema(prefix + key);
  2235. if (schema && schema.caster && op in castOps) {
  2236. // embedded doc schema
  2237. hasKeys = true;
  2238. if ('$each' in val) {
  2239. obj[key] = {
  2240. $each: this._castUpdateVal(schema, val.$each, op)
  2241. };
  2242. if (val.$slice != null) {
  2243. obj[key].$slice = val.$slice | 0;
  2244. }
  2245. if (val.$sort) {
  2246. obj[key].$sort = val.$sort;
  2247. }
  2248. if (!!val.$position || val.$position === 0) {
  2249. obj[key].$position = val.$position;
  2250. }
  2251. } else {
  2252. obj[key] = this._castUpdateVal(schema, val, op);
  2253. }
  2254. } else if (op === '$currentDate') {
  2255. // $currentDate can take an object
  2256. obj[key] = this._castUpdateVal(schema, val, op);
  2257. hasKeys = true;
  2258. } else if (op === '$set' && schema) {
  2259. obj[key] = this._castUpdateVal(schema, val, op);
  2260. hasKeys = true;
  2261. } else {
  2262. var pathToCheck = (prefix + key);
  2263. var v = this.model.schema._getPathType(pathToCheck);
  2264. var _strict = 'strict' in this._mongooseOptions ?
  2265. this._mongooseOptions.strict :
  2266. ((useNestedStrict && v.schema) || this.schema).options.strict;
  2267. if (v.pathType === 'undefined') {
  2268. if (_strict === 'throw') {
  2269. throw new StrictModeError(pathToCheck);
  2270. } else if (_strict) {
  2271. delete obj[key];
  2272. continue;
  2273. }
  2274. }
  2275. // gh-2314
  2276. // we should be able to set a schema-less field
  2277. // to an empty object literal
  2278. hasKeys |= this._walkUpdatePath(val, op, prefix + key) ||
  2279. (utils.isObject(val) && Object.keys(val).length === 0);
  2280. }
  2281. } else {
  2282. var checkPath = (key === '$each' || key === '$or' || key === '$and') ?
  2283. pref : prefix + key;
  2284. schema = this._getSchema(checkPath);
  2285. var pathDetails = this.model.schema._getPathType(checkPath);
  2286. var isStrict = 'strict' in this._mongooseOptions ?
  2287. this._mongooseOptions.strict :
  2288. ((useNestedStrict && pathDetails.schema) || this.schema).options.strict;
  2289. var skip = isStrict &&
  2290. !schema &&
  2291. !/real|nested/.test(pathDetails.pathType);
  2292. if (skip) {
  2293. if (isStrict === 'throw') {
  2294. throw new StrictModeError(prefix + key);
  2295. } else {
  2296. delete obj[key];
  2297. }
  2298. } else {
  2299. // gh-1845 temporary fix: ignore $rename. See gh-3027 for tracking
  2300. // improving this.
  2301. if (op === '$rename') {
  2302. hasKeys = true;
  2303. continue;
  2304. }
  2305. hasKeys = true;
  2306. obj[key] = this._castUpdateVal(schema, val, op, key);
  2307. }
  2308. }
  2309. }
  2310. return hasKeys;
  2311. };
  2312. /**
  2313. * Casts `val` according to `schema` and atomic `op`.
  2314. *
  2315. * @param {Schema} schema
  2316. * @param {Object} val
  2317. * @param {String} op - the atomic operator ($pull, $set, etc)
  2318. * @param {String} [$conditional]
  2319. * @api private
  2320. */
  2321. Query.prototype._castUpdateVal = function _castUpdateVal(schema, val, op, $conditional) {
  2322. if (!schema) {
  2323. // non-existing schema path
  2324. return op in numberOps
  2325. ? Number(val)
  2326. : val;
  2327. }
  2328. var cond = schema.caster && op in castOps &&
  2329. (utils.isObject(val) || Array.isArray(val));
  2330. if (cond) {
  2331. // Cast values for ops that add data to MongoDB.
  2332. // Ensures embedded documents get ObjectIds etc.
  2333. var tmp = schema.cast(val);
  2334. if (Array.isArray(val)) {
  2335. val = tmp;
  2336. } else if (Array.isArray(tmp)) {
  2337. val = tmp[0];
  2338. } else {
  2339. val = tmp;
  2340. }
  2341. }
  2342. if (op in numberOps) {
  2343. if (op === '$inc') {
  2344. return schema.castForQuery(val);
  2345. }
  2346. return Number(val);
  2347. }
  2348. if (op === '$currentDate') {
  2349. if (typeof val === 'object') {
  2350. return {$type: val.$type};
  2351. }
  2352. return Boolean(val);
  2353. }
  2354. if (/^\$/.test($conditional)) {
  2355. return schema.castForQuery($conditional, val);
  2356. }
  2357. return schema.castForQuery(val);
  2358. };
  2359. /*!
  2360. * castQuery
  2361. * @api private
  2362. */
  2363. function castQuery(query) {
  2364. try {
  2365. return query.cast(query.model);
  2366. } catch (err) {
  2367. return err;
  2368. }
  2369. }
  2370. /*!
  2371. * castDoc
  2372. * @api private
  2373. */
  2374. function castDoc(query, overwrite) {
  2375. try {
  2376. return query._castUpdate(query._update, overwrite);
  2377. } catch (err) {
  2378. return err;
  2379. }
  2380. }
  2381. /**
  2382. * Specifies paths which should be populated with other documents.
  2383. *
  2384. * ####Example:
  2385. *
  2386. * Kitten.findOne().populate('owner').exec(function (err, kitten) {
  2387. * console.log(kitten.owner.name) // Max
  2388. * })
  2389. *
  2390. * Kitten.find().populate({
  2391. * path: 'owner'
  2392. * , select: 'name'
  2393. * , match: { color: 'black' }
  2394. * , options: { sort: { name: -1 }}
  2395. * }).exec(function (err, kittens) {
  2396. * console.log(kittens[0].owner.name) // Zoopa
  2397. * })
  2398. *
  2399. * // alternatively
  2400. * Kitten.find().populate('owner', 'name', null, {sort: { name: -1 }}).exec(function (err, kittens) {
  2401. * console.log(kittens[0].owner.name) // Zoopa
  2402. * })
  2403. *
  2404. * 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.
  2405. *
  2406. * @param {Object|String} path either the path to populate or an object specifying all parameters
  2407. * @param {Object|String} [select] Field selection for the population query
  2408. * @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.
  2409. * @param {Object} [match] Conditions for the population query
  2410. * @param {Object} [options] Options for the population query (sort, etc)
  2411. * @see population ./populate.html
  2412. * @see Query#select #query_Query-select
  2413. * @see Model.populate #model_Model.populate
  2414. * @return {Query} this
  2415. * @api public
  2416. */
  2417. Query.prototype.populate = function() {
  2418. var res = utils.populate.apply(null, arguments);
  2419. var opts = this._mongooseOptions;
  2420. if (!utils.isObject(opts.populate)) {
  2421. opts.populate = {};
  2422. }
  2423. var pop = opts.populate;
  2424. for (var i = 0; i < res.length; ++i) {
  2425. var path = res[i].path;
  2426. if (pop[path] && pop[path].populate && res[i].populate) {
  2427. res[i].populate = pop[path].populate.concat(res[i].populate);
  2428. }
  2429. pop[res[i].path] = res[i];
  2430. }
  2431. return this;
  2432. };
  2433. /**
  2434. * Casts this query to the schema of `model`
  2435. *
  2436. * ####Note
  2437. *
  2438. * If `obj` is present, it is cast instead of this query.
  2439. *
  2440. * @param {Model} model
  2441. * @param {Object} [obj]
  2442. * @return {Object}
  2443. * @api public
  2444. */
  2445. Query.prototype.cast = function(model, obj) {
  2446. obj || (obj = this._conditions);
  2447. try {
  2448. return cast(model.schema, obj, {
  2449. upsert: this.options && this.options.upsert,
  2450. strict: (this.options && this.options.strict) ||
  2451. (model.schema.options && model.schema.options.strict)
  2452. });
  2453. } catch (err) {
  2454. // CastError, assign model
  2455. if (typeof err.setModel === 'function') {
  2456. err.setModel(model);
  2457. }
  2458. throw err;
  2459. }
  2460. };
  2461. /**
  2462. * Casts selected field arguments for field selection with mongo 2.2
  2463. *
  2464. * query.select({ ids: { $elemMatch: { $in: [hexString] }})
  2465. *
  2466. * @param {Object} fields
  2467. * @see https://github.com/Automattic/mongoose/issues/1091
  2468. * @see http://docs.mongodb.org/manual/reference/projection/elemMatch/
  2469. * @api private
  2470. */
  2471. Query.prototype._castFields = function _castFields(fields) {
  2472. var selected,
  2473. elemMatchKeys,
  2474. keys,
  2475. key,
  2476. out,
  2477. i;
  2478. if (fields) {
  2479. keys = Object.keys(fields);
  2480. elemMatchKeys = [];
  2481. i = keys.length;
  2482. // collect $elemMatch args
  2483. while (i--) {
  2484. key = keys[i];
  2485. if (fields[key].$elemMatch) {
  2486. selected || (selected = {});
  2487. selected[key] = fields[key];
  2488. elemMatchKeys.push(key);
  2489. }
  2490. }
  2491. }
  2492. if (selected) {
  2493. // they passed $elemMatch, cast em
  2494. try {
  2495. out = this.cast(this.model, selected);
  2496. } catch (err) {
  2497. return err;
  2498. }
  2499. // apply the casted field args
  2500. i = elemMatchKeys.length;
  2501. while (i--) {
  2502. key = elemMatchKeys[i];
  2503. fields[key] = out[key];
  2504. }
  2505. }
  2506. return fields;
  2507. };
  2508. /**
  2509. * Applies schematype selected options to this query.
  2510. * @api private
  2511. */
  2512. Query.prototype._applyPaths = function applyPaths() {
  2513. // determine if query is selecting or excluding fields
  2514. var fields = this._fields,
  2515. exclude,
  2516. keys,
  2517. ki;
  2518. if (fields) {
  2519. keys = Object.keys(fields);
  2520. ki = keys.length;
  2521. while (ki--) {
  2522. if (keys[ki][0] === '+') continue;
  2523. exclude = fields[keys[ki]] === 0;
  2524. break;
  2525. }
  2526. }
  2527. // if selecting, apply default schematype select:true fields
  2528. // if excluding, apply schematype select:false fields
  2529. var selected = [],
  2530. excluded = [],
  2531. seen = [];
  2532. var analyzePath = function(path, type) {
  2533. if (typeof type.selected !== 'boolean') return;
  2534. var plusPath = '+' + path;
  2535. if (fields && plusPath in fields) {
  2536. // forced inclusion
  2537. delete fields[plusPath];
  2538. // if there are other fields being included, add this one
  2539. // if no other included fields, leave this out (implied inclusion)
  2540. if (exclude === false && keys.length > 1 && !~keys.indexOf(path)) {
  2541. fields[path] = 1;
  2542. }
  2543. return;
  2544. }
  2545. // check for parent exclusions
  2546. var root = path.split('.')[0];
  2547. if (~excluded.indexOf(root)) return;
  2548. (type.selected ? selected : excluded).push(path);
  2549. };
  2550. var analyzeSchema = function(schema, prefix) {
  2551. prefix || (prefix = '');
  2552. // avoid recursion
  2553. if (~seen.indexOf(schema)) return;
  2554. seen.push(schema);
  2555. schema.eachPath(function(path, type) {
  2556. if (prefix) path = prefix + '.' + path;
  2557. analyzePath(path, type);
  2558. // array of subdocs?
  2559. if (type.schema) {
  2560. analyzeSchema(type.schema, path);
  2561. }
  2562. });
  2563. };
  2564. analyzeSchema(this.model.schema);
  2565. switch (exclude) {
  2566. case true:
  2567. excluded.length && this.select('-' + excluded.join(' -'));
  2568. break;
  2569. case false:
  2570. if (this.model.schema && this.model.schema.paths['_id'] &&
  2571. this.model.schema.paths['_id'].options && this.model.schema.paths['_id'].options.select === false) {
  2572. selected.push('-_id');
  2573. }
  2574. selected.length && this.select(selected.join(' '));
  2575. break;
  2576. case undefined:
  2577. // user didn't specify fields, implies returning all fields.
  2578. // only need to apply excluded fields
  2579. excluded.length && this.select('-' + excluded.join(' -'));
  2580. break;
  2581. }
  2582. seen = excluded = selected = keys = fields = null;
  2583. };
  2584. /**
  2585. * Returns a Node.js 0.8 style [read stream](http://nodejs.org/docs/v0.8.21/api/stream.html#stream_readable_stream) interface.
  2586. *
  2587. * ####Example
  2588. *
  2589. * // follows the nodejs 0.8 stream api
  2590. * Thing.find({ name: /^hello/ }).stream().pipe(res)
  2591. *
  2592. * // manual streaming
  2593. * var stream = Thing.find({ name: /^hello/ }).stream();
  2594. *
  2595. * stream.on('data', function (doc) {
  2596. * // do something with the mongoose document
  2597. * }).on('error', function (err) {
  2598. * // handle the error
  2599. * }).on('close', function () {
  2600. * // the stream is closed
  2601. * });
  2602. *
  2603. * ####Valid options
  2604. *
  2605. * - `transform`: optional function which accepts a mongoose document. The return value of the function will be emitted on `data`.
  2606. *
  2607. * ####Example
  2608. *
  2609. * // JSON.stringify all documents before emitting
  2610. * var stream = Thing.find().stream({ transform: JSON.stringify });
  2611. * stream.pipe(writeStream);
  2612. *
  2613. * @return {QueryStream}
  2614. * @param {Object} [options]
  2615. * @see QueryStream
  2616. * @api public
  2617. */
  2618. Query.prototype.stream = function stream(opts) {
  2619. this._applyPaths();
  2620. this._fields = this._castFields(this._fields);
  2621. return new QueryStream(this, opts);
  2622. };
  2623. Query.prototype.stream = util.deprecate(Query.prototype.stream, 'Mongoose: ' +
  2624. 'Query.prototype.stream() is deprecated in mongoose >= 4.5.0, ' +
  2625. 'use Query.prototype.cursor() instead');
  2626. /**
  2627. * Returns a wrapper around a [mongodb driver cursor](http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html).
  2628. * A QueryCursor exposes a [Streams3](https://strongloop.com/strongblog/whats-new-io-js-beta-streams3/)-compatible
  2629. * interface, as well as a `.next()` function.
  2630. *
  2631. * ####Example
  2632. *
  2633. * // There are 2 ways to use a cursor. First, as a stream:
  2634. * Thing.
  2635. * find({ name: /^hello/ }).
  2636. * cursor().
  2637. * on('data', function(doc) { console.log(doc); }).
  2638. * on('end', function() { console.log('Done!'); });
  2639. *
  2640. * // Or you can use `.next()` to manually get the next doc in the stream.
  2641. * // `.next()` returns a promise, so you can use promises or callbacks.
  2642. * var cursor = Thing.find({ name: /^hello/ }).cursor();
  2643. * cursor.next(function(error, doc) {
  2644. * console.log(doc);
  2645. * });
  2646. *
  2647. * // Because `.next()` returns a promise, you can use co
  2648. * // to easily iterate through all documents without loading them
  2649. * // all into memory.
  2650. * co(function*() {
  2651. * const cursor = Thing.find({ name: /^hello/ }).cursor();
  2652. * for (let doc = yield cursor.next(); doc != null; doc = yield cursor.next()) {
  2653. * console.log(doc);
  2654. * }
  2655. * });
  2656. *
  2657. * ####Valid options
  2658. *
  2659. * - `transform`: optional function which accepts a mongoose document. The return value of the function will be emitted on `data` and returned by `.next()`.
  2660. *
  2661. * @return {QueryCursor}
  2662. * @param {Object} [options]
  2663. * @see QueryCursor
  2664. * @api public
  2665. */
  2666. Query.prototype.cursor = function cursor(opts) {
  2667. this._applyPaths();
  2668. this._fields = this._castFields(this._fields);
  2669. this.setOptions({ fields: this._fieldsForExec() });
  2670. if (opts) {
  2671. this.setOptions(opts);
  2672. }
  2673. try {
  2674. this.cast(this.model);
  2675. } catch (err) {
  2676. return (new QueryCursor(this, this.options))._markError(err);
  2677. }
  2678. return new QueryCursor(this, this.options);
  2679. };
  2680. // the rest of these are basically to support older Mongoose syntax with mquery
  2681. /**
  2682. * _DEPRECATED_ Alias of `maxScan`
  2683. *
  2684. * @deprecated
  2685. * @see maxScan #query_Query-maxScan
  2686. * @method maxscan
  2687. * @memberOf Query
  2688. */
  2689. Query.prototype.maxscan = Query.base.maxScan;
  2690. /**
  2691. * Sets the tailable option (for use with capped collections).
  2692. *
  2693. * ####Example
  2694. *
  2695. * query.tailable() // true
  2696. * query.tailable(true)
  2697. * query.tailable(false)
  2698. *
  2699. * ####Note
  2700. *
  2701. * Cannot be used with `distinct()`
  2702. *
  2703. * @param {Boolean} bool defaults to true
  2704. * @param {Object} [opts] options to set
  2705. * @param {Number} [opts.numberOfRetries] if cursor is exhausted, retry this many times before giving up
  2706. * @param {Number} [opts.tailableRetryInterval] if cursor is exhausted, wait this many milliseconds before retrying
  2707. * @see tailable http://docs.mongodb.org/manual/tutorial/create-tailable-cursor/
  2708. * @api public
  2709. */
  2710. Query.prototype.tailable = function(val, opts) {
  2711. // we need to support the tailable({ awaitdata : true }) as well as the
  2712. // tailable(true, {awaitdata :true}) syntax that mquery does not support
  2713. if (val && val.constructor.name === 'Object') {
  2714. opts = val;
  2715. val = true;
  2716. }
  2717. if (val === undefined) {
  2718. val = true;
  2719. }
  2720. if (opts && typeof opts === 'object') {
  2721. for (var key in opts) {
  2722. if (key === 'awaitdata') {
  2723. // For backwards compatibility
  2724. this.options[key] = !!opts[key];
  2725. } else {
  2726. this.options[key] = opts[key];
  2727. }
  2728. }
  2729. }
  2730. return Query.base.tailable.call(this, val);
  2731. };
  2732. /**
  2733. * Declares an intersects query for `geometry()`.
  2734. *
  2735. * ####Example
  2736. *
  2737. * query.where('path').intersects().geometry({
  2738. * type: 'LineString'
  2739. * , coordinates: [[180.0, 11.0], [180, 9.0]]
  2740. * })
  2741. *
  2742. * query.where('path').intersects({
  2743. * type: 'LineString'
  2744. * , coordinates: [[180.0, 11.0], [180, 9.0]]
  2745. * })
  2746. *
  2747. * ####NOTE:
  2748. *
  2749. * **MUST** be used after `where()`.
  2750. *
  2751. * ####NOTE:
  2752. *
  2753. * 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).
  2754. *
  2755. * @method intersects
  2756. * @memberOf Query
  2757. * @param {Object} [arg]
  2758. * @return {Query} this
  2759. * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/
  2760. * @see geoIntersects http://docs.mongodb.org/manual/reference/operator/geoIntersects/
  2761. * @api public
  2762. */
  2763. /**
  2764. * Specifies a `$geometry` condition
  2765. *
  2766. * ####Example
  2767. *
  2768. * var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]]
  2769. * query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA })
  2770. *
  2771. * // or
  2772. * var polyB = [[ 0, 0 ], [ 1, 1 ]]
  2773. * query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB })
  2774. *
  2775. * // or
  2776. * var polyC = [ 0, 0 ]
  2777. * query.where('loc').within().geometry({ type: 'Point', coordinates: polyC })
  2778. *
  2779. * // or
  2780. * query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC })
  2781. *
  2782. * The argument is assigned to the most recent path passed to `where()`.
  2783. *
  2784. * ####NOTE:
  2785. *
  2786. * `geometry()` **must** come after either `intersects()` or `within()`.
  2787. *
  2788. * The `object` argument must contain `type` and `coordinates` properties.
  2789. * - type {String}
  2790. * - coordinates {Array}
  2791. *
  2792. * @method geometry
  2793. * @memberOf Query
  2794. * @param {Object} object Must contain a `type` property which is a String and a `coordinates` property which is an Array. See the examples.
  2795. * @return {Query} this
  2796. * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/
  2797. * @see http://docs.mongodb.org/manual/release-notes/2.4/#new-geospatial-indexes-with-geojson-and-improved-spherical-geometry
  2798. * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
  2799. * @api public
  2800. */
  2801. /**
  2802. * Specifies a `$near` or `$nearSphere` condition
  2803. *
  2804. * These operators return documents sorted by distance.
  2805. *
  2806. * ####Example
  2807. *
  2808. * query.where('loc').near({ center: [10, 10] });
  2809. * query.where('loc').near({ center: [10, 10], maxDistance: 5 });
  2810. * query.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true });
  2811. * query.near('loc', { center: [10, 10], maxDistance: 5 });
  2812. *
  2813. * @method near
  2814. * @memberOf Query
  2815. * @param {String} [path]
  2816. * @param {Object} val
  2817. * @return {Query} this
  2818. * @see $near http://docs.mongodb.org/manual/reference/operator/near/
  2819. * @see $nearSphere http://docs.mongodb.org/manual/reference/operator/nearSphere/
  2820. * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/
  2821. * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
  2822. * @api public
  2823. */
  2824. /*!
  2825. * Overwriting mquery is needed to support a couple different near() forms found in older
  2826. * versions of mongoose
  2827. * near([1,1])
  2828. * near(1,1)
  2829. * near(field, [1,2])
  2830. * near(field, 1, 2)
  2831. * In addition to all of the normal forms supported by mquery
  2832. */
  2833. Query.prototype.near = function() {
  2834. var params = [];
  2835. var sphere = this._mongooseOptions.nearSphere;
  2836. // TODO refactor
  2837. if (arguments.length === 1) {
  2838. if (Array.isArray(arguments[0])) {
  2839. params.push({center: arguments[0], spherical: sphere});
  2840. } else if (typeof arguments[0] === 'string') {
  2841. // just passing a path
  2842. params.push(arguments[0]);
  2843. } else if (utils.isObject(arguments[0])) {
  2844. if (typeof arguments[0].spherical !== 'boolean') {
  2845. arguments[0].spherical = sphere;
  2846. }
  2847. params.push(arguments[0]);
  2848. } else {
  2849. throw new TypeError('invalid argument');
  2850. }
  2851. } else if (arguments.length === 2) {
  2852. if (typeof arguments[0] === 'number' && typeof arguments[1] === 'number') {
  2853. params.push({center: [arguments[0], arguments[1]], spherical: sphere});
  2854. } else if (typeof arguments[0] === 'string' && Array.isArray(arguments[1])) {
  2855. params.push(arguments[0]);
  2856. params.push({center: arguments[1], spherical: sphere});
  2857. } else if (typeof arguments[0] === 'string' && utils.isObject(arguments[1])) {
  2858. params.push(arguments[0]);
  2859. if (typeof arguments[1].spherical !== 'boolean') {
  2860. arguments[1].spherical = sphere;
  2861. }
  2862. params.push(arguments[1]);
  2863. } else {
  2864. throw new TypeError('invalid argument');
  2865. }
  2866. } else if (arguments.length === 3) {
  2867. if (typeof arguments[0] === 'string' && typeof arguments[1] === 'number'
  2868. && typeof arguments[2] === 'number') {
  2869. params.push(arguments[0]);
  2870. params.push({center: [arguments[1], arguments[2]], spherical: sphere});
  2871. } else {
  2872. throw new TypeError('invalid argument');
  2873. }
  2874. } else {
  2875. throw new TypeError('invalid argument');
  2876. }
  2877. return Query.base.near.apply(this, params);
  2878. };
  2879. /**
  2880. * _DEPRECATED_ Specifies a `$nearSphere` condition
  2881. *
  2882. * ####Example
  2883. *
  2884. * query.where('loc').nearSphere({ center: [10, 10], maxDistance: 5 });
  2885. *
  2886. * **Deprecated.** Use `query.near()` instead with the `spherical` option set to `true`.
  2887. *
  2888. * ####Example
  2889. *
  2890. * query.where('loc').near({ center: [10, 10], spherical: true });
  2891. *
  2892. * @deprecated
  2893. * @see near() #query_Query-near
  2894. * @see $near http://docs.mongodb.org/manual/reference/operator/near/
  2895. * @see $nearSphere http://docs.mongodb.org/manual/reference/operator/nearSphere/
  2896. * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/
  2897. */
  2898. Query.prototype.nearSphere = function() {
  2899. this._mongooseOptions.nearSphere = true;
  2900. this.near.apply(this, arguments);
  2901. return this;
  2902. };
  2903. /**
  2904. * Specifies a $polygon condition
  2905. *
  2906. * ####Example
  2907. *
  2908. * query.where('loc').within().polygon([10,20], [13, 25], [7,15])
  2909. * query.polygon('loc', [10,20], [13, 25], [7,15])
  2910. *
  2911. * @method polygon
  2912. * @memberOf Query
  2913. * @param {String|Array} [path]
  2914. * @param {Array|Object} [coordinatePairs...]
  2915. * @return {Query} this
  2916. * @see $polygon http://docs.mongodb.org/manual/reference/operator/polygon/
  2917. * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
  2918. * @api public
  2919. */
  2920. /**
  2921. * Specifies a $box condition
  2922. *
  2923. * ####Example
  2924. *
  2925. * var lowerLeft = [40.73083, -73.99756]
  2926. * var upperRight= [40.741404, -73.988135]
  2927. *
  2928. * query.where('loc').within().box(lowerLeft, upperRight)
  2929. * query.box({ ll : lowerLeft, ur : upperRight })
  2930. *
  2931. * @method box
  2932. * @memberOf Query
  2933. * @see $box http://docs.mongodb.org/manual/reference/operator/box/
  2934. * @see within() Query#within #query_Query-within
  2935. * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
  2936. * @param {Object} val
  2937. * @param [Array] Upper Right Coords
  2938. * @return {Query} this
  2939. * @api public
  2940. */
  2941. /*!
  2942. * this is needed to support the mongoose syntax of:
  2943. * box(field, { ll : [x,y], ur : [x2,y2] })
  2944. * box({ ll : [x,y], ur : [x2,y2] })
  2945. */
  2946. Query.prototype.box = function(ll, ur) {
  2947. if (!Array.isArray(ll) && utils.isObject(ll)) {
  2948. ur = ll.ur;
  2949. ll = ll.ll;
  2950. }
  2951. return Query.base.box.call(this, ll, ur);
  2952. };
  2953. /**
  2954. * Specifies a $center or $centerSphere condition.
  2955. *
  2956. * ####Example
  2957. *
  2958. * var area = { center: [50, 50], radius: 10, unique: true }
  2959. * query.where('loc').within().circle(area)
  2960. * // alternatively
  2961. * query.circle('loc', area);
  2962. *
  2963. * // spherical calculations
  2964. * var area = { center: [50, 50], radius: 10, unique: true, spherical: true }
  2965. * query.where('loc').within().circle(area)
  2966. * // alternatively
  2967. * query.circle('loc', area);
  2968. *
  2969. * New in 3.7.0
  2970. *
  2971. * @method circle
  2972. * @memberOf Query
  2973. * @param {String} [path]
  2974. * @param {Object} area
  2975. * @return {Query} this
  2976. * @see $center http://docs.mongodb.org/manual/reference/operator/center/
  2977. * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/
  2978. * @see $geoWithin http://docs.mongodb.org/manual/reference/operator/geoWithin/
  2979. * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
  2980. * @api public
  2981. */
  2982. /**
  2983. * _DEPRECATED_ Alias for [circle](#query_Query-circle)
  2984. *
  2985. * **Deprecated.** Use [circle](#query_Query-circle) instead.
  2986. *
  2987. * @deprecated
  2988. * @method center
  2989. * @memberOf Query
  2990. * @api public
  2991. */
  2992. Query.prototype.center = Query.base.circle;
  2993. /**
  2994. * _DEPRECATED_ Specifies a $centerSphere condition
  2995. *
  2996. * **Deprecated.** Use [circle](#query_Query-circle) instead.
  2997. *
  2998. * ####Example
  2999. *
  3000. * var area = { center: [50, 50], radius: 10 };
  3001. * query.where('loc').within().centerSphere(area);
  3002. *
  3003. * @deprecated
  3004. * @param {String} [path]
  3005. * @param {Object} val
  3006. * @return {Query} this
  3007. * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
  3008. * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/
  3009. * @api public
  3010. */
  3011. Query.prototype.centerSphere = function() {
  3012. if (arguments[0] && arguments[0].constructor.name === 'Object') {
  3013. arguments[0].spherical = true;
  3014. }
  3015. if (arguments[1] && arguments[1].constructor.name === 'Object') {
  3016. arguments[1].spherical = true;
  3017. }
  3018. Query.base.circle.apply(this, arguments);
  3019. };
  3020. /**
  3021. * Determines if field selection has been made.
  3022. *
  3023. * @method selected
  3024. * @memberOf Query
  3025. * @return {Boolean}
  3026. * @api public
  3027. */
  3028. /**
  3029. * Determines if inclusive field selection has been made.
  3030. *
  3031. * query.selectedInclusively() // false
  3032. * query.select('name')
  3033. * query.selectedInclusively() // true
  3034. *
  3035. * @method selectedInclusively
  3036. * @memberOf Query
  3037. * @return {Boolean}
  3038. * @api public
  3039. */
  3040. /**
  3041. * Determines if exclusive field selection has been made.
  3042. *
  3043. * query.selectedExclusively() // false
  3044. * query.select('-name')
  3045. * query.selectedExclusively() // true
  3046. * query.selectedInclusively() // false
  3047. *
  3048. * @method selectedExclusively
  3049. * @memberOf Query
  3050. * @return {Boolean}
  3051. * @api public
  3052. */
  3053. /*!
  3054. * Export
  3055. */
  3056. module.exports = Query;