collection.js 128 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354
  1. "use strict";
  2. var checkCollectionName = require('./utils').checkCollectionName
  3. , ObjectID = require('mongodb-core').BSON.ObjectID
  4. , Long = require('mongodb-core').BSON.Long
  5. , Code = require('mongodb-core').BSON.Code
  6. , f = require('util').format
  7. , AggregationCursor = require('./aggregation_cursor')
  8. , MongoError = require('mongodb-core').MongoError
  9. , shallowClone = require('./utils').shallowClone
  10. , isObject = require('./utils').isObject
  11. , toError = require('./utils').toError
  12. , normalizeHintField = require('./utils').normalizeHintField
  13. , handleCallback = require('./utils').handleCallback
  14. , decorateCommand = require('./utils').decorateCommand
  15. , formattedOrderClause = require('./utils').formattedOrderClause
  16. , ReadPreference = require('./read_preference')
  17. , CoreReadPreference = require('mongodb-core').ReadPreference
  18. , CommandCursor = require('./command_cursor')
  19. , Define = require('./metadata')
  20. , Cursor = require('./cursor')
  21. , unordered = require('./bulk/unordered')
  22. , ordered = require('./bulk/ordered')
  23. , assign = require('./utils').assign;
  24. /**
  25. * @fileOverview The **Collection** class is an internal class that embodies a MongoDB collection
  26. * allowing for insert/update/remove/find and other command operation on that MongoDB collection.
  27. *
  28. * **COLLECTION Cannot directly be instantiated**
  29. * @example
  30. * var MongoClient = require('mongodb').MongoClient,
  31. * test = require('assert');
  32. * // Connection url
  33. * var url = 'mongodb://localhost:27017/test';
  34. * // Connect using MongoClient
  35. * MongoClient.connect(url, function(err, db) {
  36. * // Create a collection we want to drop later
  37. * var col = db.collection('createIndexExample1');
  38. * // Show that duplicate records got dropped
  39. * col.find({}).toArray(function(err, items) {
  40. * test.equal(null, err);
  41. * test.equal(4, items.length);
  42. * db.close();
  43. * });
  44. * });
  45. */
  46. /**
  47. * Create a new Collection instance (INTERNAL TYPE, do not instantiate directly)
  48. * @class
  49. * @property {string} collectionName Get the collection name.
  50. * @property {string} namespace Get the full collection namespace.
  51. * @property {object} writeConcern The current write concern values.
  52. * @property {object} readConcern The current read concern values.
  53. * @property {object} hint Get current index hint for collection.
  54. * @return {Collection} a Collection instance.
  55. */
  56. var Collection = function(db, topology, dbName, name, pkFactory, options) {
  57. checkCollectionName(name);
  58. // Unpack variables
  59. var internalHint = null;
  60. var slaveOk = options == null || options.slaveOk == null ? db.slaveOk : options.slaveOk;
  61. var serializeFunctions = options == null || options.serializeFunctions == null ? db.s.options.serializeFunctions : options.serializeFunctions;
  62. var raw = options == null || options.raw == null ? db.s.options.raw : options.raw;
  63. var promoteLongs = options == null || options.promoteLongs == null ? db.s.options.promoteLongs : options.promoteLongs;
  64. var promoteValues = options == null || options.promoteValues == null ? db.s.options.promoteValues : options.promoteValues;
  65. var promoteBuffers = options == null || options.promoteBuffers == null ? db.s.options.promoteBuffers : options.promoteBuffers;
  66. var readPreference = null;
  67. var collectionHint = null;
  68. var namespace = f("%s.%s", dbName, name);
  69. // Get the promiseLibrary
  70. var promiseLibrary = options.promiseLibrary;
  71. // No promise library selected fall back
  72. if(!promiseLibrary) {
  73. promiseLibrary = typeof global.Promise == 'function' ?
  74. global.Promise : require('es6-promise').Promise;
  75. }
  76. // Assign the right collection level readPreference
  77. if(options && options.readPreference) {
  78. readPreference = options.readPreference;
  79. } else if(db.options.readPreference) {
  80. readPreference = db.options.readPreference;
  81. }
  82. // Set custom primary key factory if provided
  83. pkFactory = pkFactory == null
  84. ? ObjectID
  85. : pkFactory;
  86. // Internal state
  87. this.s = {
  88. // Set custom primary key factory if provided
  89. pkFactory: pkFactory
  90. // Db
  91. , db: db
  92. // Topology
  93. , topology: topology
  94. // dbName
  95. , dbName: dbName
  96. // Options
  97. , options: options
  98. // Namespace
  99. , namespace: namespace
  100. // Read preference
  101. , readPreference: readPreference
  102. // SlaveOK
  103. , slaveOk: slaveOk
  104. // Serialize functions
  105. , serializeFunctions: serializeFunctions
  106. // Raw
  107. , raw: raw
  108. // promoteLongs
  109. , promoteLongs: promoteLongs
  110. // promoteValues
  111. , promoteValues: promoteValues
  112. // promoteBuffers
  113. , promoteBuffers: promoteBuffers
  114. // internalHint
  115. , internalHint: internalHint
  116. // collectionHint
  117. , collectionHint: collectionHint
  118. // Name
  119. , name: name
  120. // Promise library
  121. , promiseLibrary: promiseLibrary
  122. // Read Concern
  123. , readConcern: options.readConcern
  124. }
  125. }
  126. var define = Collection.define = new Define('Collection', Collection, false);
  127. Object.defineProperty(Collection.prototype, 'collectionName', {
  128. enumerable: true, get: function() { return this.s.name; }
  129. });
  130. Object.defineProperty(Collection.prototype, 'namespace', {
  131. enumerable: true, get: function() { return this.s.namespace; }
  132. });
  133. Object.defineProperty(Collection.prototype, 'readConcern', {
  134. enumerable: true, get: function() { return this.s.readConcern || {level: 'local'}; }
  135. });
  136. Object.defineProperty(Collection.prototype, 'writeConcern', {
  137. enumerable:true,
  138. get: function() {
  139. var ops = {};
  140. if(this.s.options.w != null) ops.w = this.s.options.w;
  141. if(this.s.options.j != null) ops.j = this.s.options.j;
  142. if(this.s.options.fsync != null) ops.fsync = this.s.options.fsync;
  143. if(this.s.options.wtimeout != null) ops.wtimeout = this.s.options.wtimeout;
  144. return ops;
  145. }
  146. });
  147. /**
  148. * @ignore
  149. */
  150. Object.defineProperty(Collection.prototype, "hint", {
  151. enumerable: true
  152. , get: function () { return this.s.collectionHint; }
  153. , set: function (v) { this.s.collectionHint = normalizeHintField(v); }
  154. });
  155. /**
  156. * Creates a cursor for a query that can be used to iterate over results from MongoDB
  157. * @method
  158. * @param {object} query The cursor query object.
  159. * @throws {MongoError}
  160. * @return {Cursor}
  161. */
  162. Collection.prototype.find = function() {
  163. var options
  164. , args = Array.prototype.slice.call(arguments, 0)
  165. , has_callback = typeof args[args.length - 1] === 'function'
  166. , has_weird_callback = typeof args[0] === 'function'
  167. , callback = has_callback ? args.pop() : (has_weird_callback ? args.shift() : null)
  168. , len = args.length
  169. , selector = len >= 1 ? args[0] : {}
  170. , fields = len >= 2 ? args[1] : undefined;
  171. if(len === 1 && has_weird_callback) {
  172. // backwards compat for callback?, options case
  173. selector = {};
  174. options = args[0];
  175. }
  176. if(len === 2 && fields !== undefined && !Array.isArray(fields)) {
  177. var fieldKeys = Object.keys(fields);
  178. var is_option = false;
  179. for(var i = 0; i < fieldKeys.length; i++) {
  180. if(testForFields[fieldKeys[i]] != null) {
  181. is_option = true;
  182. break;
  183. }
  184. }
  185. if(is_option) {
  186. options = fields;
  187. fields = undefined;
  188. } else {
  189. options = {};
  190. }
  191. } else if(len === 2 && Array.isArray(fields) && !Array.isArray(fields[0])) {
  192. var newFields = {};
  193. // Rewrite the array
  194. for(i = 0; i < fields.length; i++) {
  195. newFields[fields[i]] = 1;
  196. }
  197. // Set the fields
  198. fields = newFields;
  199. }
  200. if(3 === len) {
  201. options = args[2];
  202. }
  203. // Ensure selector is not null
  204. selector = selector == null ? {} : selector;
  205. // Validate correctness off the selector
  206. var object = selector;
  207. if(Buffer.isBuffer(object)) {
  208. var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24;
  209. if(object_size != object.length) {
  210. var error = new Error("query selector raw message size does not match message header size [" + object.length + "] != [" + object_size + "]");
  211. error.name = 'MongoError';
  212. throw error;
  213. }
  214. }
  215. // Validate correctness of the field selector
  216. object = fields;
  217. if(Buffer.isBuffer(object)) {
  218. object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24;
  219. if(object_size != object.length) {
  220. error = new Error("query fields raw message size does not match message header size [" + object.length + "] != [" + object_size + "]");
  221. error.name = 'MongoError';
  222. throw error;
  223. }
  224. }
  225. // Check special case where we are using an objectId
  226. if(selector != null && selector._bsontype == 'ObjectID') {
  227. selector = {_id:selector};
  228. }
  229. // If it's a serialized fields field we need to just let it through
  230. // user be warned it better be good
  231. if(options && options.fields && !(Buffer.isBuffer(options.fields))) {
  232. fields = {};
  233. if(Array.isArray(options.fields)) {
  234. if(!options.fields.length) {
  235. fields['_id'] = 1;
  236. } else {
  237. var l = options.fields.length;
  238. for (i = 0; i < l; i++) {
  239. fields[options.fields[i]] = 1;
  240. }
  241. }
  242. } else {
  243. fields = options.fields;
  244. }
  245. }
  246. if (!options) options = {};
  247. var newOptions = {};
  248. // Make a shallow copy of options
  249. for (var key in options) {
  250. newOptions[key] = options[key];
  251. }
  252. // Unpack options
  253. newOptions.skip = len > 3 ? args[2] : options.skip ? options.skip : 0;
  254. newOptions.limit = len > 3 ? args[3] : options.limit ? options.limit : 0;
  255. newOptions.raw = options.raw != null && typeof options.raw === 'boolean' ? options.raw : this.s.raw;
  256. newOptions.hint = options.hint != null ? normalizeHintField(options.hint) : this.s.collectionHint;
  257. newOptions.timeout = len == 5 ? args[4] : typeof options.timeout === 'undefined' ? undefined : options.timeout;
  258. // // If we have overridden slaveOk otherwise use the default db setting
  259. newOptions.slaveOk = options.slaveOk != null ? options.slaveOk : this.s.db.slaveOk;
  260. // Add read preference if needed
  261. newOptions = getReadPreference(this, newOptions, this.s.db, this);
  262. // Set slave ok to true if read preference different from primary
  263. if(newOptions.readPreference != null
  264. && (newOptions.readPreference != 'primary' || newOptions.readPreference.mode != 'primary')) {
  265. newOptions.slaveOk = true;
  266. }
  267. // Ensure the query is an object
  268. if(selector != null && typeof selector != 'object') {
  269. throw MongoError.create({message: "query selector must be an object", driver:true });
  270. }
  271. // Build the find command
  272. var findCommand = {
  273. find: this.s.namespace
  274. , limit: newOptions.limit
  275. , skip: newOptions.skip
  276. , query: selector
  277. }
  278. // Ensure we use the right await data option
  279. if(typeof newOptions.awaitdata == 'boolean') {
  280. newOptions.awaitData = newOptions.awaitdata
  281. }
  282. // Translate to new command option noCursorTimeout
  283. if(typeof newOptions.timeout == 'boolean') newOptions.noCursorTimeout = newOptions.timeout;
  284. // Merge in options to command
  285. for(var name in newOptions) {
  286. if(newOptions[name] != null) findCommand[name] = newOptions[name];
  287. }
  288. // Format the fields
  289. var formatFields = function(fields) {
  290. var object = {};
  291. if(Array.isArray(fields)) {
  292. for(var i = 0; i < fields.length; i++) {
  293. if(Array.isArray(fields[i])) {
  294. object[fields[i][0]] = fields[i][1];
  295. } else {
  296. object[fields[i][0]] = 1;
  297. }
  298. }
  299. } else {
  300. object = fields;
  301. }
  302. return object;
  303. }
  304. // Special treatment for the fields selector
  305. if(fields) findCommand.fields = formatFields(fields);
  306. // Add db object to the new options
  307. newOptions.db = this.s.db;
  308. // Add the promise library
  309. newOptions.promiseLibrary = this.s.promiseLibrary;
  310. // Set raw if available at collection level
  311. if(newOptions.raw == null && typeof this.s.raw == 'boolean') newOptions.raw = this.s.raw;
  312. // Set promoteLongs if available at collection level
  313. if(newOptions.promoteLongs == null && typeof this.s.promoteLongs == 'boolean') newOptions.promoteLongs = this.s.promoteLongs;
  314. if(newOptions.promoteValues == null && typeof this.s.promoteValues == 'boolean') newOptions.promoteValues = this.s.promoteValues;
  315. if(newOptions.promoteBuffers == null && typeof this.s.promoteBuffers == 'boolean') newOptions.promoteBuffers = this.s.promoteBuffers;
  316. // Sort options
  317. if(findCommand.sort) {
  318. findCommand.sort = formattedOrderClause(findCommand.sort);
  319. }
  320. // Set the readConcern
  321. if(this.s.readConcern) {
  322. findCommand.readConcern = this.s.readConcern;
  323. }
  324. // Decorate find command with collation options
  325. decorateWithCollation(findCommand, this, options);
  326. // Create the cursor
  327. if(typeof callback == 'function') return handleCallback(callback, null, this.s.topology.cursor(this.s.namespace, findCommand, newOptions));
  328. return this.s.topology.cursor(this.s.namespace, findCommand, newOptions);
  329. }
  330. define.classMethod('find', {callback: false, promise:false, returns: [Cursor]});
  331. /**
  332. * Inserts a single document into MongoDB. If documents passed in do not contain the **_id** field,
  333. * one will be added to each of the documents missing it by the driver, mutating the document. This behavior
  334. * can be overridden by setting the **forceServerObjectId** flag.
  335. *
  336. * @method
  337. * @param {object} doc Document to insert.
  338. * @param {object} [options=null] Optional settings.
  339. * @param {(number|string)} [options.w=null] The write concern.
  340. * @param {number} [options.wtimeout=null] The write concern timeout.
  341. * @param {boolean} [options.j=false] Specify a journal write concern.
  342. * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
  343. * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver.
  344. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
  345. * @param {Collection~insertOneWriteOpCallback} [callback] The command result callback
  346. * @return {Promise} returns Promise if no callback passed
  347. */
  348. Collection.prototype.insertOne = function(doc, options, callback) {
  349. var self = this;
  350. if(typeof options == 'function') callback = options, options = {};
  351. options = options || {};
  352. if(Array.isArray(doc) && typeof callback == 'function') {
  353. return callback(MongoError.create({message: 'doc parameter must be an object', driver:true }));
  354. } else if(Array.isArray(doc)) {
  355. return new this.s.promiseLibrary(function(resolve, reject) {
  356. reject(MongoError.create({message: 'doc parameter must be an object', driver:true }));
  357. });
  358. }
  359. // Add ignoreUndfined
  360. if(this.s.options.ignoreUndefined) {
  361. options = shallowClone(options);
  362. options.ignoreUndefined = this.s.options.ignoreUndefined;
  363. }
  364. // Execute using callback
  365. if(typeof callback == 'function') return insertOne(self, doc, options, callback);
  366. // Return a Promise
  367. return new this.s.promiseLibrary(function(resolve, reject) {
  368. insertOne(self, doc, options, function(err, r) {
  369. if(err) return reject(err);
  370. resolve(r);
  371. });
  372. });
  373. }
  374. var insertOne = function(self, doc, options, callback) {
  375. insertDocuments(self, [doc], options, function(err, r) {
  376. if(callback == null) return;
  377. if(err && callback) return callback(err);
  378. // Workaround for pre 2.6 servers
  379. if(r == null) return callback(null, {result: {ok:1}});
  380. // Add values to top level to ensure crud spec compatibility
  381. r.insertedCount = r.result.n;
  382. r.insertedId = doc._id;
  383. if(callback) callback(null, r);
  384. });
  385. }
  386. var mapInserManyResults = function(docs, r) {
  387. var ids = r.getInsertedIds();
  388. var keys = Object.keys(ids);
  389. var finalIds = new Array(keys.length);
  390. for(var i = 0; i < keys.length; i++) {
  391. if(ids[keys[i]]._id) {
  392. finalIds[ids[keys[i]].index] = ids[keys[i]]._id;
  393. }
  394. }
  395. var finalResult = {
  396. result: {ok: 1, n: r.insertedCount},
  397. ops: docs,
  398. insertedCount: r.insertedCount,
  399. insertedIds: finalIds
  400. };
  401. if(r.getLastOp()) {
  402. finalResult.result.opTime = r.getLastOp();
  403. }
  404. return finalResult;
  405. }
  406. define.classMethod('insertOne', {callback: true, promise:true});
  407. /**
  408. * Inserts an array of documents into MongoDB. If documents passed in do not contain the **_id** field,
  409. * one will be added to each of the documents missing it by the driver, mutating the document. This behavior
  410. * can be overridden by setting the **forceServerObjectId** flag.
  411. *
  412. * @method
  413. * @param {object[]} docs Documents to insert.
  414. * @param {object} [options=null] Optional settings.
  415. * @param {(number|string)} [options.w=null] The write concern.
  416. * @param {number} [options.wtimeout=null] The write concern timeout.
  417. * @param {boolean} [options.j=false] Specify a journal write concern.
  418. * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
  419. * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver.
  420. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
  421. * @param {Collection~insertWriteOpCallback} [callback] The command result callback
  422. * @return {Promise} returns Promise if no callback passed
  423. */
  424. Collection.prototype.insertMany = function(docs, options, callback) {
  425. var self = this;
  426. if(typeof options == 'function') callback = options, options = {};
  427. options = options || {ordered:true};
  428. if(!Array.isArray(docs) && typeof callback == 'function') {
  429. return callback(MongoError.create({message: 'docs parameter must be an array of documents', driver:true }));
  430. } else if(!Array.isArray(docs)) {
  431. return new this.s.promiseLibrary(function(resolve, reject) {
  432. reject(MongoError.create({message: 'docs parameter must be an array of documents', driver:true }));
  433. });
  434. }
  435. // Get the write concern options
  436. if(typeof options.checkKeys != 'boolean') {
  437. options.checkKeys = true;
  438. }
  439. // If keep going set unordered
  440. options['serializeFunctions'] = options['serializeFunctions'] || self.s.serializeFunctions;
  441. // Set up the force server object id
  442. var forceServerObjectId = typeof options.forceServerObjectId == 'boolean'
  443. ? options.forceServerObjectId : self.s.db.options.forceServerObjectId;
  444. // Do we want to force the server to assign the _id key
  445. if(forceServerObjectId !== true) {
  446. // Add _id if not specified
  447. for(var i = 0; i < docs.length; i++) {
  448. if(docs[i]._id == null) docs[i]._id = self.s.pkFactory.createPk();
  449. }
  450. }
  451. // Generate the bulk write operations
  452. var operations = [{
  453. insertMany: docs
  454. }];
  455. // Execute using callback
  456. if(typeof callback == 'function') return bulkWrite(self, operations, options, function(err, r) {
  457. if(err) return callback(err, r);
  458. callback(null, mapInserManyResults(docs, r));
  459. });
  460. // Return a Promise
  461. return new this.s.promiseLibrary(function(resolve, reject) {
  462. bulkWrite(self, operations, options, function(err, r) {
  463. if(err) return reject(err);
  464. resolve(mapInserManyResults(docs, r));
  465. });
  466. });
  467. }
  468. define.classMethod('insertMany', {callback: true, promise:true});
  469. /**
  470. * @typedef {Object} Collection~BulkWriteOpResult
  471. * @property {number} insertedCount Number of documents inserted.
  472. * @property {number} matchedCount Number of documents matched for update.
  473. * @property {number} modifiedCount Number of documents modified.
  474. * @property {number} deletedCount Number of documents deleted.
  475. * @property {number} upsertedCount Number of documents upserted.
  476. * @property {object} insertedIds Inserted document generated Id's, hash key is the index of the originating operation
  477. * @property {object} upsertedIds Upserted document generated Id's, hash key is the index of the originating operation
  478. * @property {object} result The command result object.
  479. */
  480. /**
  481. * The callback format for inserts
  482. * @callback Collection~bulkWriteOpCallback
  483. * @param {MongoError} error An error instance representing the error during the execution.
  484. * @param {Collection~BulkWriteOpResult} result The result object if the command was executed successfully.
  485. */
  486. /**
  487. * Perform a bulkWrite operation without a fluent API
  488. *
  489. * Legal operation types are
  490. *
  491. * { insertOne: { document: { a: 1 } } }
  492. *
  493. * { updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } }
  494. *
  495. * { updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } }
  496. *
  497. * { deleteOne: { filter: {c:1} } }
  498. *
  499. * { deleteMany: { filter: {c:1} } }
  500. *
  501. * { replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true}}
  502. *
  503. * If documents passed in do not contain the **_id** field,
  504. * one will be added to each of the documents missing it by the driver, mutating the document. This behavior
  505. * can be overridden by setting the **forceServerObjectId** flag.
  506. *
  507. * @method
  508. * @param {object[]} operations Bulk operations to perform.
  509. * @param {object} [options=null] Optional settings.
  510. * @param {(number|string)} [options.w=null] The write concern.
  511. * @param {number} [options.wtimeout=null] The write concern timeout.
  512. * @param {boolean} [options.j=false] Specify a journal write concern.
  513. * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
  514. * @param {boolean} [options.ordered=true] Execute write operation in ordered or unordered fashion.
  515. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
  516. * @param {Collection~bulkWriteOpCallback} [callback] The command result callback
  517. * @return {Promise} returns Promise if no callback passed
  518. */
  519. Collection.prototype.bulkWrite = function(operations, options, callback) {
  520. var self = this;
  521. if(typeof options == 'function') callback = options, options = {};
  522. options = options || {ordered:true};
  523. if(!Array.isArray(operations)) {
  524. throw MongoError.create({message: "operations must be an array of documents", driver:true });
  525. }
  526. // Execute using callback
  527. if(typeof callback == 'function') return bulkWrite(self, operations, options, callback);
  528. // Return a Promise
  529. return new this.s.promiseLibrary(function(resolve, reject) {
  530. bulkWrite(self, operations, options, function(err, r) {
  531. if(err && r == null) return reject(err);
  532. resolve(r);
  533. });
  534. });
  535. }
  536. var bulkWrite = function(self, operations, options, callback) {
  537. // Add ignoreUndfined
  538. if(self.s.options.ignoreUndefined) {
  539. options = shallowClone(options);
  540. options.ignoreUndefined = self.s.options.ignoreUndefined;
  541. }
  542. // Create the bulk operation
  543. var bulk = options.ordered == true || options.ordered == null ? self.initializeOrderedBulkOp(options) : self.initializeUnorderedBulkOp(options);
  544. // Do we have a collation
  545. var collation = false;
  546. // for each op go through and add to the bulk
  547. try {
  548. for(var i = 0; i < operations.length; i++) {
  549. // Get the operation type
  550. var key = Object.keys(operations[i])[0];
  551. // Check if we have a collation
  552. if(operations[i][key].collation) {
  553. collation = true;
  554. }
  555. // Pass to the raw bulk
  556. bulk.raw(operations[i]);
  557. }
  558. } catch(err) {
  559. return callback(err, null);
  560. }
  561. // Final options for write concern
  562. var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options);
  563. var writeCon = finalOptions.writeConcern ? finalOptions.writeConcern : {};
  564. var capabilities = self.s.topology.capabilities();
  565. // Did the user pass in a collation, check if our write server supports it
  566. if(collation && capabilities && !capabilities.commandsTakeCollation) {
  567. return callback(new MongoError(f('server/primary/mongos does not support collation')));
  568. }
  569. // Execute the bulk
  570. bulk.execute(writeCon, function(err, r) {
  571. // We have connection level error
  572. if(!r && err) return callback(err, null);
  573. // We have single error
  574. if(r && r.hasWriteErrors() && r.getWriteErrorCount() == 1) {
  575. return callback(toError(r.getWriteErrorAt(0)), r);
  576. }
  577. r.insertedCount = r.nInserted;
  578. r.matchedCount = r.nMatched;
  579. r.modifiedCount = r.nModified || 0;
  580. r.deletedCount = r.nRemoved;
  581. r.upsertedCount = r.getUpsertedIds().length;
  582. r.upsertedIds = {};
  583. r.insertedIds = {};
  584. // Update the n
  585. r.n = r.insertedCount;
  586. // Inserted documents
  587. var inserted = r.getInsertedIds();
  588. // Map inserted ids
  589. for(var i = 0; i < inserted.length; i++) {
  590. r.insertedIds[inserted[i].index] = inserted[i]._id;
  591. }
  592. // Upserted documents
  593. var upserted = r.getUpsertedIds();
  594. // Map upserted ids
  595. for(i = 0; i < upserted.length; i++) {
  596. r.upsertedIds[upserted[i].index] = upserted[i]._id;
  597. }
  598. // Check if we have write errors
  599. if(r.hasWriteErrors()) {
  600. // Get all the errors
  601. var errors = r.getWriteErrors();
  602. // Return the MongoError object
  603. return callback(toError({
  604. message: 'write operation failed', code: errors[0].code, writeErrors: errors
  605. }), r);
  606. }
  607. // Check if we have a writeConcern error
  608. if(r.getWriteConcernError()) {
  609. // Return the MongoError object
  610. return callback(toError(r.getWriteConcernError()), r);
  611. }
  612. // Return the results
  613. callback(null, r);
  614. });
  615. }
  616. var insertDocuments = function(self, docs, options, callback) {
  617. if(typeof options == 'function') callback = options, options = {};
  618. options = options || {};
  619. // Ensure we are operating on an array op docs
  620. docs = Array.isArray(docs) ? docs : [docs];
  621. // Get the write concern options
  622. var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options);
  623. if(typeof finalOptions.checkKeys != 'boolean') finalOptions.checkKeys = true;
  624. // If keep going set unordered
  625. if(finalOptions.keepGoing == true) finalOptions.ordered = false;
  626. finalOptions['serializeFunctions'] = options['serializeFunctions'] || self.s.serializeFunctions;
  627. // Set up the force server object id
  628. var forceServerObjectId = typeof options.forceServerObjectId == 'boolean'
  629. ? options.forceServerObjectId : self.s.db.options.forceServerObjectId;
  630. // Add _id if not specified
  631. if(forceServerObjectId !== true){
  632. for(var i = 0; i < docs.length; i++) {
  633. if(docs[i]._id == null) docs[i]._id = self.s.pkFactory.createPk();
  634. }
  635. }
  636. // File inserts
  637. self.s.topology.insert(self.s.namespace, docs, finalOptions, function(err, result) {
  638. if(callback == null) return;
  639. if(err) return handleCallback(callback, err);
  640. if(result == null) return handleCallback(callback, null, null);
  641. if(result.result.code) return handleCallback(callback, toError(result.result));
  642. if(result.result.writeErrors) return handleCallback(callback, toError(result.result.writeErrors[0]));
  643. // Add docs to the list
  644. result.ops = docs;
  645. // Return the results
  646. handleCallback(callback, null, result);
  647. });
  648. }
  649. define.classMethod('bulkWrite', {callback: true, promise:true});
  650. /**
  651. * @typedef {Object} Collection~WriteOpResult
  652. * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany
  653. * @property {object} connection The connection object used for the operation.
  654. * @property {object} result The command result object.
  655. */
  656. /**
  657. * The callback format for inserts
  658. * @callback Collection~writeOpCallback
  659. * @param {MongoError} error An error instance representing the error during the execution.
  660. * @param {Collection~WriteOpResult} result The result object if the command was executed successfully.
  661. */
  662. /**
  663. * @typedef {Object} Collection~insertWriteOpResult
  664. * @property {Number} insertedCount The total amount of documents inserted.
  665. * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany
  666. * @property {ObjectId[]} insertedIds All the generated _id's for the inserted documents.
  667. * @property {object} connection The connection object used for the operation.
  668. * @property {object} result The raw command result object returned from MongoDB (content might vary by server version).
  669. * @property {Number} result.ok Is 1 if the command executed correctly.
  670. * @property {Number} result.n The total count of documents inserted.
  671. */
  672. /**
  673. * @typedef {Object} Collection~insertOneWriteOpResult
  674. * @property {Number} insertedCount The total amount of documents inserted.
  675. * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany
  676. * @property {ObjectId} insertedId The driver generated ObjectId for the insert operation.
  677. * @property {object} connection The connection object used for the operation.
  678. * @property {object} result The raw command result object returned from MongoDB (content might vary by server version).
  679. * @property {Number} result.ok Is 1 if the command executed correctly.
  680. * @property {Number} result.n The total count of documents inserted.
  681. */
  682. /**
  683. * The callback format for inserts
  684. * @callback Collection~insertWriteOpCallback
  685. * @param {MongoError} error An error instance representing the error during the execution.
  686. * @param {Collection~insertWriteOpResult} result The result object if the command was executed successfully.
  687. */
  688. /**
  689. * The callback format for inserts
  690. * @callback Collection~insertOneWriteOpCallback
  691. * @param {MongoError} error An error instance representing the error during the execution.
  692. * @param {Collection~insertOneWriteOpResult} result The result object if the command was executed successfully.
  693. */
  694. /**
  695. * Inserts a single document or a an array of documents into MongoDB. If documents passed in do not contain the **_id** field,
  696. * one will be added to each of the documents missing it by the driver, mutating the document. This behavior
  697. * can be overridden by setting the **forceServerObjectId** flag.
  698. *
  699. * @method
  700. * @param {(object|object[])} docs Documents to insert.
  701. * @param {object} [options=null] Optional settings.
  702. * @param {(number|string)} [options.w=null] The write concern.
  703. * @param {number} [options.wtimeout=null] The write concern timeout.
  704. * @param {boolean} [options.j=false] Specify a journal write concern.
  705. * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
  706. * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver.
  707. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
  708. * @param {Collection~insertWriteOpCallback} [callback] The command result callback
  709. * @return {Promise} returns Promise if no callback passed
  710. * @deprecated Use insertOne, insertMany or bulkWrite
  711. */
  712. Collection.prototype.insert = function(docs, options, callback) {
  713. if(typeof options == 'function') callback = options, options = {};
  714. options = options || {ordered:false};
  715. docs = !Array.isArray(docs) ? [docs] : docs;
  716. if(options.keepGoing == true) {
  717. options.ordered = false;
  718. }
  719. return this.insertMany(docs, options, callback);
  720. }
  721. define.classMethod('insert', {callback: true, promise:true});
  722. /**
  723. * @typedef {Object} Collection~updateWriteOpResult
  724. * @property {Object} result The raw result returned from MongoDB, field will vary depending on server version.
  725. * @property {Number} result.ok Is 1 if the command executed correctly.
  726. * @property {Number} result.n The total count of documents scanned.
  727. * @property {Number} result.nModified The total count of documents modified.
  728. * @property {Object} connection The connection object used for the operation.
  729. * @property {Number} matchedCount The number of documents that matched the filter.
  730. * @property {Number} modifiedCount The number of documents that were modified.
  731. * @property {Number} upsertedCount The number of documents upserted.
  732. * @property {Object} upsertedId The upserted id.
  733. * @property {ObjectId} upsertedId._id The upserted _id returned from the server.
  734. */
  735. /**
  736. * The callback format for inserts
  737. * @callback Collection~updateWriteOpCallback
  738. * @param {MongoError} error An error instance representing the error during the execution.
  739. * @param {Collection~updateWriteOpResult} result The result object if the command was executed successfully.
  740. */
  741. /**
  742. * Update a single document on MongoDB
  743. * @method
  744. * @param {object} filter The Filter used to select the document to update
  745. * @param {object} update The update operations to be applied to the document
  746. * @param {object} [options=null] Optional settings.
  747. * @param {boolean} [options.upsert=false] Update operation is an upsert.
  748. * @param {(number|string)} [options.w=null] The write concern.
  749. * @param {number} [options.wtimeout=null] The write concern timeout.
  750. * @param {boolean} [options.j=false] Specify a journal write concern.
  751. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
  752. * @param {Collection~updateWriteOpCallback} [callback] The command result callback
  753. * @return {Promise} returns Promise if no callback passed
  754. */
  755. Collection.prototype.updateOne = function(filter, update, options, callback) {
  756. var self = this;
  757. if(typeof options == 'function') callback = options, options = {};
  758. options = shallowClone(options)
  759. // Add ignoreUndfined
  760. if(this.s.options.ignoreUndefined) {
  761. options = shallowClone(options);
  762. options.ignoreUndefined = this.s.options.ignoreUndefined;
  763. }
  764. // Execute using callback
  765. if(typeof callback == 'function') return updateOne(self, filter, update, options, callback);
  766. // Return a Promise
  767. return new this.s.promiseLibrary(function(resolve, reject) {
  768. updateOne(self, filter, update, options, function(err, r) {
  769. if(err) return reject(err);
  770. resolve(r);
  771. });
  772. });
  773. }
  774. var updateOne = function(self, filter, update, options, callback) {
  775. // Set single document update
  776. options.multi = false;
  777. // Execute update
  778. updateDocuments(self, filter, update, options, function(err, r) {
  779. if(callback == null) return;
  780. if(err && callback) return callback(err);
  781. if(r == null) return callback(null, {result: {ok:1}});
  782. r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n;
  783. r.upsertedId = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? r.result.upserted[0] : null;
  784. r.upsertedCount = Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0;
  785. r.matchedCount = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n;
  786. if(callback) callback(null, r);
  787. });
  788. }
  789. define.classMethod('updateOne', {callback: true, promise:true});
  790. /**
  791. * Replace a document on MongoDB
  792. * @method
  793. * @param {object} filter The Filter used to select the document to update
  794. * @param {object} doc The Document that replaces the matching document
  795. * @param {object} [options=null] Optional settings.
  796. * @param {boolean} [options.upsert=false] Update operation is an upsert.
  797. * @param {(number|string)} [options.w=null] The write concern.
  798. * @param {number} [options.wtimeout=null] The write concern timeout.
  799. * @param {boolean} [options.j=false] Specify a journal write concern.
  800. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
  801. * @param {Collection~updateWriteOpCallback} [callback] The command result callback
  802. * @return {Promise} returns Promise if no callback passed
  803. */
  804. Collection.prototype.replaceOne = function(filter, doc, options, callback) {
  805. var self = this;
  806. if(typeof options == 'function') callback = options, options = {};
  807. options = shallowClone(options)
  808. // Add ignoreUndfined
  809. if(this.s.options.ignoreUndefined) {
  810. options = shallowClone(options);
  811. options.ignoreUndefined = this.s.options.ignoreUndefined;
  812. }
  813. // Execute using callback
  814. if(typeof callback == 'function') return replaceOne(self, filter, doc, options, callback);
  815. // Return a Promise
  816. return new this.s.promiseLibrary(function(resolve, reject) {
  817. replaceOne(self, filter, doc, options, function(err, r) {
  818. if(err) return reject(err);
  819. resolve(r);
  820. });
  821. });
  822. }
  823. var replaceOne = function(self, filter, doc, options, callback) {
  824. // Set single document update
  825. options.multi = false;
  826. // Execute update
  827. updateDocuments(self, filter, doc, options, function(err, r) {
  828. if(callback == null) return;
  829. if(err && callback) return callback(err);
  830. if(r == null) return callback(null, {result: {ok:1}});
  831. r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n;
  832. r.upsertedId = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? r.result.upserted[0] : null;
  833. r.upsertedCount = Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0;
  834. r.matchedCount = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n;
  835. r.ops = [doc];
  836. if(callback) callback(null, r);
  837. });
  838. }
  839. define.classMethod('replaceOne', {callback: true, promise:true});
  840. /**
  841. * Update multiple documents on MongoDB
  842. * @method
  843. * @param {object} filter The Filter used to select the document to update
  844. * @param {object} update The update operations to be applied to the document
  845. * @param {object} [options=null] Optional settings.
  846. * @param {boolean} [options.upsert=false] Update operation is an upsert.
  847. * @param {(number|string)} [options.w=null] The write concern.
  848. * @param {number} [options.wtimeout=null] The write concern timeout.
  849. * @param {boolean} [options.j=false] Specify a journal write concern.
  850. * @param {Collection~updateWriteOpCallback} [callback] The command result callback
  851. * @return {Promise} returns Promise if no callback passed
  852. */
  853. Collection.prototype.updateMany = function(filter, update, options, callback) {
  854. var self = this;
  855. if(typeof options == 'function') callback = options, options = {};
  856. options = shallowClone(options)
  857. // Add ignoreUndfined
  858. if(this.s.options.ignoreUndefined) {
  859. options = shallowClone(options);
  860. options.ignoreUndefined = this.s.options.ignoreUndefined;
  861. }
  862. // Execute using callback
  863. if(typeof callback == 'function') return updateMany(self, filter, update, options, callback);
  864. // Return a Promise
  865. return new this.s.promiseLibrary(function(resolve, reject) {
  866. updateMany(self, filter, update, options, function(err, r) {
  867. if(err) return reject(err);
  868. resolve(r);
  869. });
  870. });
  871. }
  872. var updateMany = function(self, filter, update, options, callback) {
  873. // Set single document update
  874. options.multi = true;
  875. // Execute update
  876. updateDocuments(self, filter, update, options, function(err, r) {
  877. if(callback == null) return;
  878. if(err && callback) return callback(err);
  879. if(r == null) return callback(null, {result: {ok:1}});
  880. r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n;
  881. r.upsertedId = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? r.result.upserted[0] : null;
  882. r.upsertedCount = Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0;
  883. r.matchedCount = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n;
  884. if(callback) callback(null, r);
  885. });
  886. }
  887. define.classMethod('updateMany', {callback: true, promise:true});
  888. var updateDocuments = function(self, selector, document, options, callback) {
  889. if('function' === typeof options) callback = options, options = null;
  890. if(options == null) options = {};
  891. if(!('function' === typeof callback)) callback = null;
  892. // If we are not providing a selector or document throw
  893. if(selector == null || typeof selector != 'object') return callback(toError("selector must be a valid JavaScript object"));
  894. if(document == null || typeof document != 'object') return callback(toError("document must be a valid JavaScript object"));
  895. // Get the write concern options
  896. var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options);
  897. // Do we return the actual result document
  898. // Either use override on the function, or go back to default on either the collection
  899. // level or db
  900. finalOptions['serializeFunctions'] = options['serializeFunctions'] || self.s.serializeFunctions;
  901. // Execute the operation
  902. var op = {q: selector, u: document};
  903. op.upsert = typeof options.upsert == 'boolean' ? options.upsert : false;
  904. op.multi = typeof options.multi == 'boolean' ? options.multi : false;
  905. // Have we specified collation
  906. decorateWithCollation(finalOptions, self, options);
  907. // Update options
  908. self.s.topology.update(self.s.namespace, [op], finalOptions, function(err, result) {
  909. if(callback == null) return;
  910. if(err) return handleCallback(callback, err, null);
  911. if(result == null) return handleCallback(callback, null, null);
  912. if(result.result.code) return handleCallback(callback, toError(result.result));
  913. if(result.result.writeErrors) return handleCallback(callback, toError(result.result.writeErrors[0]));
  914. // Return the results
  915. handleCallback(callback, null, result);
  916. });
  917. }
  918. /**
  919. * Updates documents.
  920. * @method
  921. * @param {object} selector The selector for the update operation.
  922. * @param {object} document The update document.
  923. * @param {object} [options=null] Optional settings.
  924. * @param {(number|string)} [options.w=null] The write concern.
  925. * @param {number} [options.wtimeout=null] The write concern timeout.
  926. * @param {boolean} [options.j=false] Specify a journal write concern.
  927. * @param {boolean} [options.upsert=false] Update operation is an upsert.
  928. * @param {boolean} [options.multi=false] Update one/all documents with operation.
  929. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
  930. * @param {object} [options.collation=null] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
  931. * @param {Collection~writeOpCallback} [callback] The command result callback
  932. * @throws {MongoError}
  933. * @return {Promise} returns Promise if no callback passed
  934. * @deprecated use updateOne, updateMany or bulkWrite
  935. */
  936. Collection.prototype.update = function(selector, document, options, callback) {
  937. var self = this;
  938. // Add ignoreUndfined
  939. if(this.s.options.ignoreUndefined) {
  940. options = shallowClone(options);
  941. options.ignoreUndefined = this.s.options.ignoreUndefined;
  942. }
  943. // Execute using callback
  944. if(typeof callback == 'function') return updateDocuments(self, selector, document, options, callback);
  945. // Return a Promise
  946. return new this.s.promiseLibrary(function(resolve, reject) {
  947. updateDocuments(self, selector, document, options, function(err, r) {
  948. if(err) return reject(err);
  949. resolve(r);
  950. });
  951. });
  952. }
  953. define.classMethod('update', {callback: true, promise:true});
  954. /**
  955. * @typedef {Object} Collection~deleteWriteOpResult
  956. * @property {Object} result The raw result returned from MongoDB, field will vary depending on server version.
  957. * @property {Number} result.ok Is 1 if the command executed correctly.
  958. * @property {Number} result.n The total count of documents deleted.
  959. * @property {Object} connection The connection object used for the operation.
  960. * @property {Number} deletedCount The number of documents deleted.
  961. */
  962. /**
  963. * The callback format for inserts
  964. * @callback Collection~deleteWriteOpCallback
  965. * @param {MongoError} error An error instance representing the error during the execution.
  966. * @param {Collection~deleteWriteOpResult} result The result object if the command was executed successfully.
  967. */
  968. /**
  969. * Delete a document on MongoDB
  970. * @method
  971. * @param {object} filter The Filter used to select the document to remove
  972. * @param {object} [options=null] Optional settings.
  973. * @param {(number|string)} [options.w=null] The write concern.
  974. * @param {number} [options.wtimeout=null] The write concern timeout.
  975. * @param {boolean} [options.j=false] Specify a journal write concern.
  976. * @param {Collection~deleteWriteOpCallback} [callback] The command result callback
  977. * @return {Promise} returns Promise if no callback passed
  978. */
  979. Collection.prototype.deleteOne = function(filter, options, callback) {
  980. var self = this;
  981. if(typeof options == 'function') callback = options, options = {};
  982. options = shallowClone(options);
  983. // Add ignoreUndfined
  984. if(this.s.options.ignoreUndefined) {
  985. options = shallowClone(options);
  986. options.ignoreUndefined = this.s.options.ignoreUndefined;
  987. }
  988. // Execute using callback
  989. if(typeof callback == 'function') return deleteOne(self, filter, options, callback);
  990. // Return a Promise
  991. return new this.s.promiseLibrary(function(resolve, reject) {
  992. deleteOne(self, filter, options, function(err, r) {
  993. if(err) return reject(err);
  994. resolve(r);
  995. });
  996. });
  997. }
  998. var deleteOne = function(self, filter, options, callback) {
  999. options.single = true;
  1000. removeDocuments(self, filter, options, function(err, r) {
  1001. if(callback == null) return;
  1002. if(err && callback) return callback(err);
  1003. if(r == null) return callback(null, {result: {ok:1}});
  1004. r.deletedCount = r.result.n;
  1005. if(callback) callback(null, r);
  1006. });
  1007. }
  1008. define.classMethod('deleteOne', {callback: true, promise:true});
  1009. Collection.prototype.removeOne = Collection.prototype.deleteOne;
  1010. define.classMethod('removeOne', {callback: true, promise:true});
  1011. /**
  1012. * Delete multiple documents on MongoDB
  1013. * @method
  1014. * @param {object} filter The Filter used to select the documents to remove
  1015. * @param {object} [options=null] Optional settings.
  1016. * @param {(number|string)} [options.w=null] The write concern.
  1017. * @param {number} [options.wtimeout=null] The write concern timeout.
  1018. * @param {boolean} [options.j=false] Specify a journal write concern.
  1019. * @param {Collection~deleteWriteOpCallback} [callback] The command result callback
  1020. * @return {Promise} returns Promise if no callback passed
  1021. */
  1022. Collection.prototype.deleteMany = function(filter, options, callback) {
  1023. var self = this;
  1024. if(typeof options == 'function') callback = options, options = {};
  1025. options = shallowClone(options);
  1026. // Add ignoreUndfined
  1027. if(this.s.options.ignoreUndefined) {
  1028. options = shallowClone(options);
  1029. options.ignoreUndefined = this.s.options.ignoreUndefined;
  1030. }
  1031. // Execute using callback
  1032. if(typeof callback == 'function') return deleteMany(self, filter, options, callback);
  1033. // Return a Promise
  1034. return new this.s.promiseLibrary(function(resolve, reject) {
  1035. deleteMany(self, filter, options, function(err, r) {
  1036. if(err) return reject(err);
  1037. resolve(r);
  1038. });
  1039. });
  1040. }
  1041. var deleteMany = function(self, filter, options, callback) {
  1042. options.single = false;
  1043. removeDocuments(self, filter, options, function(err, r) {
  1044. if(callback == null) return;
  1045. if(err && callback) return callback(err);
  1046. if(r == null) return callback(null, {result: {ok:1}});
  1047. r.deletedCount = r.result.n;
  1048. if(callback) callback(null, r);
  1049. });
  1050. }
  1051. var removeDocuments = function(self, selector, options, callback) {
  1052. if(typeof options == 'function') {
  1053. callback = options, options = {};
  1054. } else if (typeof selector === 'function') {
  1055. callback = selector;
  1056. options = {};
  1057. selector = {};
  1058. }
  1059. // Create an empty options object if the provided one is null
  1060. options = options || {};
  1061. // Get the write concern options
  1062. var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options);
  1063. // If selector is null set empty
  1064. if(selector == null) selector = {};
  1065. // Build the op
  1066. var op = {q: selector, limit: 0};
  1067. if(options.single) op.limit = 1;
  1068. // Have we specified collation
  1069. decorateWithCollation(finalOptions, self, options);
  1070. // Execute the remove
  1071. self.s.topology.remove(self.s.namespace, [op], finalOptions, function(err, result) {
  1072. if(callback == null) return;
  1073. if(err) return handleCallback(callback, err, null);
  1074. if(result == null) return handleCallback(callback, null, null);
  1075. if(result.result.code) return handleCallback(callback, toError(result.result));
  1076. if(result.result.writeErrors) return handleCallback(callback, toError(result.result.writeErrors[0]));
  1077. // Return the results
  1078. handleCallback(callback, null, result);
  1079. });
  1080. }
  1081. define.classMethod('deleteMany', {callback: true, promise:true});
  1082. Collection.prototype.removeMany = Collection.prototype.deleteMany;
  1083. define.classMethod('removeMany', {callback: true, promise:true});
  1084. /**
  1085. * Remove documents.
  1086. * @method
  1087. * @param {object} selector The selector for the update operation.
  1088. * @param {object} [options=null] Optional settings.
  1089. * @param {(number|string)} [options.w=null] The write concern.
  1090. * @param {number} [options.wtimeout=null] The write concern timeout.
  1091. * @param {boolean} [options.j=false] Specify a journal write concern.
  1092. * @param {boolean} [options.single=false] Removes the first document found.
  1093. * @param {Collection~writeOpCallback} [callback] The command result callback
  1094. * @return {Promise} returns Promise if no callback passed
  1095. * @deprecated use deleteOne, deleteMany or bulkWrite
  1096. */
  1097. Collection.prototype.remove = function(selector, options, callback) {
  1098. var self = this;
  1099. // Add ignoreUndfined
  1100. if(this.s.options.ignoreUndefined) {
  1101. options = shallowClone(options);
  1102. options.ignoreUndefined = this.s.options.ignoreUndefined;
  1103. }
  1104. // Execute using callback
  1105. if(typeof callback == 'function') return removeDocuments(self, selector, options, callback);
  1106. // Return a Promise
  1107. return new this.s.promiseLibrary(function(resolve, reject) {
  1108. removeDocuments(self, selector, options, function(err, r) {
  1109. if(err) return reject(err);
  1110. resolve(r);
  1111. });
  1112. });
  1113. }
  1114. define.classMethod('remove', {callback: true, promise:true});
  1115. /**
  1116. * Save a document. Simple full document replacement function. Not recommended for efficiency, use atomic
  1117. * operators and update instead for more efficient operations.
  1118. * @method
  1119. * @param {object} doc Document to save
  1120. * @param {object} [options=null] Optional settings.
  1121. * @param {(number|string)} [options.w=null] The write concern.
  1122. * @param {number} [options.wtimeout=null] The write concern timeout.
  1123. * @param {boolean} [options.j=false] Specify a journal write concern.
  1124. * @param {Collection~writeOpCallback} [callback] The command result callback
  1125. * @return {Promise} returns Promise if no callback passed
  1126. * @deprecated use insertOne, insertMany, updateOne or updateMany
  1127. */
  1128. Collection.prototype.save = function(doc, options, callback) {
  1129. var self = this;
  1130. if(typeof options == 'function') callback = options, options = {};
  1131. options = options || {};
  1132. // Add ignoreUndfined
  1133. if(this.s.options.ignoreUndefined) {
  1134. options = shallowClone(options);
  1135. options.ignoreUndefined = this.s.options.ignoreUndefined;
  1136. }
  1137. // Execute using callback
  1138. if(typeof callback == 'function') return save(self, doc, options, callback);
  1139. // Return a Promise
  1140. return new this.s.promiseLibrary(function(resolve, reject) {
  1141. save(self, doc, options, function(err, r) {
  1142. if(err) return reject(err);
  1143. resolve(r);
  1144. });
  1145. });
  1146. }
  1147. var save = function(self, doc, options, callback) {
  1148. // Get the write concern options
  1149. var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options);
  1150. // Establish if we need to perform an insert or update
  1151. if(doc._id != null) {
  1152. finalOptions.upsert = true;
  1153. return updateDocuments(self, {_id: doc._id}, doc, finalOptions, callback);
  1154. }
  1155. // Insert the document
  1156. insertDocuments(self, [doc], options, function(err, r) {
  1157. if(callback == null) return;
  1158. if(doc == null) return handleCallback(callback, null, null);
  1159. if(err) return handleCallback(callback, err, null);
  1160. handleCallback(callback, null, r);
  1161. });
  1162. }
  1163. define.classMethod('save', {callback: true, promise:true});
  1164. /**
  1165. * The callback format for results
  1166. * @callback Collection~resultCallback
  1167. * @param {MongoError} error An error instance representing the error during the execution.
  1168. * @param {object} result The result object if the command was executed successfully.
  1169. */
  1170. /**
  1171. * Fetches the first document that matches the query
  1172. * @method
  1173. * @param {object} query Query for find Operation
  1174. * @param {object} [options=null] Optional settings.
  1175. * @param {number} [options.limit=0] Sets the limit of documents returned in the query.
  1176. * @param {(array|object)} [options.sort=null] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc.
  1177. * @param {object} [options.fields=null] The fields to return in the query. Object of fields to include or exclude (not both), {'a':1}
  1178. * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination).
  1179. * @param {Object} [options.hint=null] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1}
  1180. * @param {boolean} [options.explain=false] Explain the query instead of returning the data.
  1181. * @param {boolean} [options.snapshot=false] Snapshot query.
  1182. * @param {boolean} [options.timeout=false] Specify if the cursor can timeout.
  1183. * @param {boolean} [options.tailable=false] Specify if the cursor is tailable.
  1184. * @param {number} [options.batchSize=0] Set the batchSize for the getMoreCommand when iterating over the query results.
  1185. * @param {boolean} [options.returnKey=false] Only return the index key.
  1186. * @param {number} [options.maxScan=null] Limit the number of items to scan.
  1187. * @param {number} [options.min=null] Set index bounds.
  1188. * @param {number} [options.max=null] Set index bounds.
  1189. * @param {boolean} [options.showDiskLoc=false] Show disk location of results.
  1190. * @param {string} [options.comment=null] You can put a $comment field on a query to make looking in the profiler logs simpler.
  1191. * @param {boolean} [options.raw=false] Return document results as raw BSON buffers.
  1192. * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution.
  1193. * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types.
  1194. * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers.
  1195. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  1196. * @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system
  1197. * @param {number} [options.maxTimeMS=null] Number of miliseconds to wait before aborting the query.
  1198. * @param {object} [options.collation=null] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
  1199. * @param {Collection~resultCallback} [callback] The command result callback
  1200. * @return {Promise} returns Promise if no callback passed
  1201. */
  1202. Collection.prototype.findOne = function() {
  1203. var self = this;
  1204. var args = Array.prototype.slice.call(arguments, 0);
  1205. var callback = args.pop();
  1206. if(typeof callback != 'function') args.push(callback);
  1207. // Execute using callback
  1208. if(typeof callback == 'function') return findOne(self, args, callback);
  1209. // Return a Promise
  1210. return new this.s.promiseLibrary(function(resolve, reject) {
  1211. findOne(self, args, function(err, r) {
  1212. if(err) return reject(err);
  1213. resolve(r);
  1214. });
  1215. });
  1216. }
  1217. var findOne = function(self, args, callback) {
  1218. var cursor = self.find.apply(self, args).limit(-1).batchSize(1);
  1219. // Return the item
  1220. cursor.next(function(err, item) {
  1221. if(err != null) return handleCallback(callback, toError(err), null);
  1222. handleCallback(callback, null, item);
  1223. });
  1224. }
  1225. define.classMethod('findOne', {callback: true, promise:true});
  1226. /**
  1227. * The callback format for the collection method, must be used if strict is specified
  1228. * @callback Collection~collectionResultCallback
  1229. * @param {MongoError} error An error instance representing the error during the execution.
  1230. * @param {Collection} collection The collection instance.
  1231. */
  1232. /**
  1233. * Rename the collection.
  1234. *
  1235. * @method
  1236. * @param {string} newName New name of of the collection.
  1237. * @param {object} [options=null] Optional settings.
  1238. * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists.
  1239. * @param {Collection~collectionResultCallback} [callback] The results callback
  1240. * @return {Promise} returns Promise if no callback passed
  1241. */
  1242. Collection.prototype.rename = function(newName, opt, callback) {
  1243. var self = this;
  1244. if(typeof opt == 'function') callback = opt, opt = {};
  1245. opt = assign({}, opt, {readPreference: ReadPreference.PRIMARY});
  1246. // Execute using callback
  1247. if(typeof callback == 'function') return rename(self, newName, opt, callback);
  1248. // Return a Promise
  1249. return new this.s.promiseLibrary(function(resolve, reject) {
  1250. rename(self, newName, opt, function(err, r) {
  1251. if(err) return reject(err);
  1252. resolve(r);
  1253. });
  1254. });
  1255. }
  1256. var rename = function(self, newName, opt, callback) {
  1257. // Check the collection name
  1258. checkCollectionName(newName);
  1259. // Build the command
  1260. var renameCollection = f("%s.%s", self.s.dbName, self.s.name);
  1261. var toCollection = f("%s.%s", self.s.dbName, newName);
  1262. var dropTarget = typeof opt.dropTarget == 'boolean' ? opt.dropTarget : false;
  1263. var cmd = {'renameCollection':renameCollection, 'to':toCollection, 'dropTarget':dropTarget};
  1264. // Decorate command with writeConcern if supported
  1265. decorateWithWriteConcern(cmd, self, opt);
  1266. // Execute against admin
  1267. self.s.db.admin().command(cmd, opt, function(err, doc) {
  1268. if(err) return handleCallback(callback, err, null);
  1269. // We have an error
  1270. if(doc.errmsg) return handleCallback(callback, toError(doc), null);
  1271. try {
  1272. return handleCallback(callback, null, new Collection(self.s.db, self.s.topology, self.s.dbName, newName, self.s.pkFactory, self.s.options));
  1273. } catch(err) {
  1274. return handleCallback(callback, toError(err), null);
  1275. }
  1276. });
  1277. }
  1278. define.classMethod('rename', {callback: true, promise:true});
  1279. /**
  1280. * Drop the collection from the database, removing it permanently. New accesses will create a new collection.
  1281. *
  1282. * @method
  1283. * @param {object} [options=null] Optional settings.
  1284. * @param {Collection~resultCallback} [callback] The results callback
  1285. * @return {Promise} returns Promise if no callback passed
  1286. */
  1287. Collection.prototype.drop = function(options, callback) {
  1288. var self = this;
  1289. if(typeof options == 'function') callback = options, options = {};
  1290. options = options || {};
  1291. // Execute using callback
  1292. if(typeof callback == 'function') return self.s.db.dropCollection(self.s.name, options, callback);
  1293. // Return a Promise
  1294. return new this.s.promiseLibrary(function(resolve, reject) {
  1295. self.s.db.dropCollection(self.s.name, options, function(err, r) {
  1296. if(err) return reject(err);
  1297. resolve(r);
  1298. });
  1299. });
  1300. }
  1301. define.classMethod('drop', {callback: true, promise:true});
  1302. /**
  1303. * Returns the options of the collection.
  1304. *
  1305. * @method
  1306. * @param {Collection~resultCallback} [callback] The results callback
  1307. * @return {Promise} returns Promise if no callback passed
  1308. */
  1309. Collection.prototype.options = function(callback) {
  1310. var self = this;
  1311. // Execute using callback
  1312. if(typeof callback == 'function') return options(self, callback);
  1313. // Return a Promise
  1314. return new this.s.promiseLibrary(function(resolve, reject) {
  1315. options(self, function(err, r) {
  1316. if(err) return reject(err);
  1317. resolve(r);
  1318. });
  1319. });
  1320. }
  1321. var options = function(self, callback) {
  1322. self.s.db.listCollections({name: self.s.name}).toArray(function(err, collections) {
  1323. if(err) return handleCallback(callback, err);
  1324. if(collections.length == 0) {
  1325. return handleCallback(callback, MongoError.create({message: f("collection %s not found", self.s.namespace), driver:true }));
  1326. }
  1327. handleCallback(callback, err, collections[0].options || null);
  1328. });
  1329. }
  1330. define.classMethod('options', {callback: true, promise:true});
  1331. /**
  1332. * Returns if the collection is a capped collection
  1333. *
  1334. * @method
  1335. * @param {Collection~resultCallback} [callback] The results callback
  1336. * @return {Promise} returns Promise if no callback passed
  1337. */
  1338. Collection.prototype.isCapped = function(callback) {
  1339. var self = this;
  1340. // Execute using callback
  1341. if(typeof callback == 'function') return isCapped(self, callback);
  1342. // Return a Promise
  1343. return new this.s.promiseLibrary(function(resolve, reject) {
  1344. isCapped(self, function(err, r) {
  1345. if(err) return reject(err);
  1346. resolve(r);
  1347. });
  1348. });
  1349. }
  1350. var isCapped = function(self, callback) {
  1351. self.options(function(err, document) {
  1352. if(err) return handleCallback(callback, err);
  1353. handleCallback(callback, null, document && document.capped);
  1354. });
  1355. }
  1356. define.classMethod('isCapped', {callback: true, promise:true});
  1357. /**
  1358. * Creates an index on the db and collection collection.
  1359. * @method
  1360. * @param {(string|object)} fieldOrSpec Defines the index.
  1361. * @param {object} [options=null] Optional settings.
  1362. * @param {(number|string)} [options.w=null] The write concern.
  1363. * @param {number} [options.wtimeout=null] The write concern timeout.
  1364. * @param {boolean} [options.j=false] Specify a journal write concern.
  1365. * @param {boolean} [options.unique=false] Creates an unique index.
  1366. * @param {boolean} [options.sparse=false] Creates a sparse index.
  1367. * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible.
  1368. * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value
  1369. * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates.
  1370. * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates.
  1371. * @param {number} [options.v=null] Specify the format version of the indexes.
  1372. * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)
  1373. * @param {string} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes)
  1374. * @param {object} [options.partialFilterExpression=null] Creates a partial index based on the given filter object (MongoDB 3.2 or higher)
  1375. * @param {object} [options.collation=null] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
  1376. * @param {Collection~resultCallback} [callback] The command result callback
  1377. * @return {Promise} returns Promise if no callback passed
  1378. */
  1379. Collection.prototype.createIndex = function(fieldOrSpec, options, callback) {
  1380. var self = this;
  1381. var args = Array.prototype.slice.call(arguments, 1);
  1382. callback = args.pop();
  1383. if(typeof callback != 'function') args.push(callback);
  1384. options = args.length ? args.shift() || {} : {};
  1385. options = typeof callback === 'function' ? options : callback;
  1386. options = options == null ? {} : options;
  1387. // Execute using callback
  1388. if(typeof callback == 'function') return createIndex(self, fieldOrSpec, options, callback);
  1389. // Return a Promise
  1390. return new this.s.promiseLibrary(function(resolve, reject) {
  1391. createIndex(self, fieldOrSpec, options, function(err, r) {
  1392. if(err) return reject(err);
  1393. resolve(r);
  1394. });
  1395. });
  1396. }
  1397. var createIndex = function(self, fieldOrSpec, options, callback) {
  1398. self.s.db.createIndex(self.s.name, fieldOrSpec, options, callback);
  1399. }
  1400. define.classMethod('createIndex', {callback: true, promise:true});
  1401. /**
  1402. * Creates multiple indexes in the collection, this method is only supported for
  1403. * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported
  1404. * error. Index specifications are defined at http://docs.mongodb.org/manual/reference/command/createIndexes/.
  1405. * @method
  1406. * @param {array} indexSpecs An array of index specifications to be created
  1407. * @param {Collection~resultCallback} [callback] The command result callback
  1408. * @return {Promise} returns Promise if no callback passed
  1409. */
  1410. Collection.prototype.createIndexes = function(indexSpecs, callback) {
  1411. var self = this;
  1412. // Execute using callback
  1413. if(typeof callback == 'function') return createIndexes(self, indexSpecs, callback);
  1414. // Return a Promise
  1415. return new this.s.promiseLibrary(function(resolve, reject) {
  1416. createIndexes(self, indexSpecs, function(err, r) {
  1417. if(err) return reject(err);
  1418. resolve(r);
  1419. });
  1420. });
  1421. }
  1422. var createIndexes = function(self, indexSpecs, callback) {
  1423. var capabilities = self.s.topology.capabilities();
  1424. // Ensure we generate the correct name if the parameter is not set
  1425. for(var i = 0; i < indexSpecs.length; i++) {
  1426. if(indexSpecs[i].name == null) {
  1427. var keys = [];
  1428. // Did the user pass in a collation, check if our write server supports it
  1429. if(indexSpecs[i].collation && capabilities && !capabilities.commandsTakeCollation) {
  1430. return callback(new MongoError(f('server/primary/mongos does not support collation')));
  1431. }
  1432. for(var name in indexSpecs[i].key) {
  1433. keys.push(f('%s_%s', name, indexSpecs[i].key[name]));
  1434. }
  1435. // Set the name
  1436. indexSpecs[i].name = keys.join('_');
  1437. }
  1438. }
  1439. // Execute the index
  1440. self.s.db.command({
  1441. createIndexes: self.s.name, indexes: indexSpecs
  1442. }, { readPreference: ReadPreference.PRIMARY }, callback);
  1443. }
  1444. define.classMethod('createIndexes', {callback: true, promise:true});
  1445. /**
  1446. * Drops an index from this collection.
  1447. * @method
  1448. * @param {string} indexName Name of the index to drop.
  1449. * @param {object} [options=null] Optional settings.
  1450. * @param {(number|string)} [options.w=null] The write concern.
  1451. * @param {number} [options.wtimeout=null] The write concern timeout.
  1452. * @param {boolean} [options.j=false] Specify a journal write concern.
  1453. * @param {Collection~resultCallback} [callback] The command result callback
  1454. * @return {Promise} returns Promise if no callback passed
  1455. */
  1456. Collection.prototype.dropIndex = function(indexName, options, callback) {
  1457. var self = this;
  1458. var args = Array.prototype.slice.call(arguments, 1);
  1459. callback = args.pop();
  1460. if(typeof callback != 'function') args.push(callback);
  1461. options = args.length ? args.shift() || {} : {};
  1462. // Run only against primary
  1463. options.readPreference = ReadPreference.PRIMARY;
  1464. // Execute using callback
  1465. if(typeof callback == 'function') return dropIndex(self, indexName, options, callback);
  1466. // Return a Promise
  1467. return new this.s.promiseLibrary(function(resolve, reject) {
  1468. dropIndex(self, indexName, options, function(err, r) {
  1469. if(err) return reject(err);
  1470. resolve(r);
  1471. });
  1472. });
  1473. }
  1474. var dropIndex = function(self, indexName, options, callback) {
  1475. // Delete index command
  1476. var cmd = {'dropIndexes':self.s.name, 'index':indexName};
  1477. // Decorate command with writeConcern if supported
  1478. decorateWithWriteConcern(cmd, self, options);
  1479. // Execute command
  1480. self.s.db.command(cmd, options, function(err, result) {
  1481. if(typeof callback != 'function') return;
  1482. if(err) return handleCallback(callback, err, null);
  1483. handleCallback(callback, null, result);
  1484. });
  1485. }
  1486. define.classMethod('dropIndex', {callback: true, promise:true});
  1487. /**
  1488. * Drops all indexes from this collection.
  1489. * @method
  1490. * @param {Collection~resultCallback} [callback] The command result callback
  1491. * @return {Promise} returns Promise if no callback passed
  1492. */
  1493. Collection.prototype.dropIndexes = function(options, callback) {
  1494. var self = this;
  1495. // Do we have options
  1496. if(typeof options == 'function') callback = options, options = {};
  1497. options = options || {};
  1498. // Execute using callback
  1499. if(typeof callback == 'function') return dropIndexes(self, options, callback);
  1500. // Return a Promise
  1501. return new this.s.promiseLibrary(function(resolve, reject) {
  1502. dropIndexes(self, function(err, r) {
  1503. if(err) return reject(err);
  1504. resolve(r);
  1505. });
  1506. });
  1507. }
  1508. var dropIndexes = function(self, options, callback) {
  1509. self.dropIndex('*', options, function(err) {
  1510. if(err) return handleCallback(callback, err, false);
  1511. handleCallback(callback, null, true);
  1512. });
  1513. }
  1514. define.classMethod('dropIndexes', {callback: true, promise:true});
  1515. /**
  1516. * Drops all indexes from this collection.
  1517. * @method
  1518. * @deprecated use dropIndexes
  1519. * @param {Collection~resultCallback} callback The command result callback
  1520. * @return {Promise} returns Promise if no [callback] passed
  1521. */
  1522. Collection.prototype.dropAllIndexes = Collection.prototype.dropIndexes;
  1523. define.classMethod('dropAllIndexes', {callback: true, promise:true});
  1524. /**
  1525. * Reindex all indexes on the collection
  1526. * Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections.
  1527. * @method
  1528. * @param {Collection~resultCallback} [callback] The command result callback
  1529. * @return {Promise} returns Promise if no callback passed
  1530. */
  1531. Collection.prototype.reIndex = function(options, callback) {
  1532. var self = this;
  1533. if(typeof options == 'function') callback = options, options = {};
  1534. options = options || {};
  1535. // Execute using callback
  1536. if(typeof callback == 'function') return reIndex(self, options, callback);
  1537. // Return a Promise
  1538. return new this.s.promiseLibrary(function(resolve, reject) {
  1539. reIndex(self, options, function(err, r) {
  1540. if(err) return reject(err);
  1541. resolve(r);
  1542. });
  1543. });
  1544. }
  1545. var reIndex = function(self, options, callback) {
  1546. // Reindex
  1547. var cmd = {'reIndex':self.s.name};
  1548. // Decorate command with writeConcern if supported
  1549. decorateWithWriteConcern(cmd, self, options);
  1550. // Execute the command
  1551. self.s.db.command(cmd, options, function(err, result) {
  1552. if(callback == null) return;
  1553. if(err) return handleCallback(callback, err, null);
  1554. handleCallback(callback, null, result.ok ? true : false);
  1555. });
  1556. }
  1557. define.classMethod('reIndex', {callback: true, promise:true});
  1558. /**
  1559. * Get the list of all indexes information for the collection.
  1560. *
  1561. * @method
  1562. * @param {object} [options=null] Optional settings.
  1563. * @param {number} [options.batchSize=null] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection
  1564. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  1565. * @return {CommandCursor}
  1566. */
  1567. Collection.prototype.listIndexes = function(options) {
  1568. options = options || {};
  1569. // Clone the options
  1570. options = shallowClone(options);
  1571. // Determine the read preference in the options.
  1572. options = getReadPreference(this, options, this.s.db, this);
  1573. // Set the CommandCursor constructor
  1574. options.cursorFactory = CommandCursor;
  1575. // Set the promiseLibrary
  1576. options.promiseLibrary = this.s.promiseLibrary;
  1577. if(!this.s.topology.capabilities()) {
  1578. throw new MongoError('cannot connect to server');
  1579. }
  1580. // We have a list collections command
  1581. if(this.s.topology.capabilities().hasListIndexesCommand) {
  1582. // Cursor options
  1583. var cursor = options.batchSize ? {batchSize: options.batchSize} : {}
  1584. // Build the command
  1585. var command = { listIndexes: this.s.name, cursor: cursor };
  1586. // Execute the cursor
  1587. cursor = this.s.topology.cursor(f('%s.$cmd', this.s.dbName), command, options);
  1588. // Do we have a readPreference, apply it
  1589. if(options.readPreference) cursor.setReadPreference(options.readPreference);
  1590. // Return the cursor
  1591. return cursor;
  1592. }
  1593. // Get the namespace
  1594. var ns = f('%s.system.indexes', this.s.dbName);
  1595. // Get the query
  1596. cursor = this.s.topology.cursor(ns, {find: ns, query: {ns: this.s.namespace}}, options);
  1597. // Do we have a readPreference, apply it
  1598. if(options.readPreference) cursor.setReadPreference(options.readPreference);
  1599. // Set the passed in batch size if one was provided
  1600. if(options.batchSize) cursor = cursor.batchSize(options.batchSize);
  1601. // Return the cursor
  1602. return cursor;
  1603. };
  1604. define.classMethod('listIndexes', {callback: false, promise:false, returns: [CommandCursor]});
  1605. /**
  1606. * Ensures that an index exists, if it does not it creates it
  1607. * @method
  1608. * @deprecated use createIndexes instead
  1609. * @param {(string|object)} fieldOrSpec Defines the index.
  1610. * @param {object} [options=null] Optional settings.
  1611. * @param {(number|string)} [options.w=null] The write concern.
  1612. * @param {number} [options.wtimeout=null] The write concern timeout.
  1613. * @param {boolean} [options.j=false] Specify a journal write concern.
  1614. * @param {boolean} [options.unique=false] Creates an unique index.
  1615. * @param {boolean} [options.sparse=false] Creates a sparse index.
  1616. * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible.
  1617. * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value
  1618. * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates.
  1619. * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates.
  1620. * @param {number} [options.v=null] Specify the format version of the indexes.
  1621. * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)
  1622. * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes)
  1623. * @param {object} [options.collation=null] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
  1624. * @param {Collection~resultCallback} [callback] The command result callback
  1625. * @return {Promise} returns Promise if no callback passed
  1626. */
  1627. Collection.prototype.ensureIndex = function(fieldOrSpec, options, callback) {
  1628. var self = this;
  1629. if(typeof options == 'function') callback = options, options = {};
  1630. options = options || {};
  1631. // Execute using callback
  1632. if(typeof callback == 'function') return ensureIndex(self, fieldOrSpec, options, callback);
  1633. // Return a Promise
  1634. return new this.s.promiseLibrary(function(resolve, reject) {
  1635. ensureIndex(self, fieldOrSpec, options, function(err, r) {
  1636. if(err) return reject(err);
  1637. resolve(r);
  1638. });
  1639. });
  1640. }
  1641. var ensureIndex = function(self, fieldOrSpec, options, callback) {
  1642. self.s.db.ensureIndex(self.s.name, fieldOrSpec, options, callback);
  1643. }
  1644. define.classMethod('ensureIndex', {callback: true, promise:true});
  1645. /**
  1646. * Checks if one or more indexes exist on the collection, fails on first non-existing index
  1647. * @method
  1648. * @param {(string|array)} indexes One or more index names to check.
  1649. * @param {Collection~resultCallback} [callback] The command result callback
  1650. * @return {Promise} returns Promise if no callback passed
  1651. */
  1652. Collection.prototype.indexExists = function(indexes, callback) {
  1653. var self = this;
  1654. // Execute using callback
  1655. if(typeof callback == 'function') return indexExists(self, indexes, callback);
  1656. // Return a Promise
  1657. return new this.s.promiseLibrary(function(resolve, reject) {
  1658. indexExists(self, indexes, function(err, r) {
  1659. if(err) return reject(err);
  1660. resolve(r);
  1661. });
  1662. });
  1663. }
  1664. var indexExists = function(self, indexes, callback) {
  1665. self.indexInformation(function(err, indexInformation) {
  1666. // If we have an error return
  1667. if(err != null) return handleCallback(callback, err, null);
  1668. // Let's check for the index names
  1669. if(!Array.isArray(indexes)) return handleCallback(callback, null, indexInformation[indexes] != null);
  1670. // Check in list of indexes
  1671. for(var i = 0; i < indexes.length; i++) {
  1672. if(indexInformation[indexes[i]] == null) {
  1673. return handleCallback(callback, null, false);
  1674. }
  1675. }
  1676. // All keys found return true
  1677. return handleCallback(callback, null, true);
  1678. });
  1679. }
  1680. define.classMethod('indexExists', {callback: true, promise:true});
  1681. /**
  1682. * Retrieves this collections index info.
  1683. * @method
  1684. * @param {object} [options=null] Optional settings.
  1685. * @param {boolean} [options.full=false] Returns the full raw index information.
  1686. * @param {Collection~resultCallback} [callback] The command result callback
  1687. * @return {Promise} returns Promise if no callback passed
  1688. */
  1689. Collection.prototype.indexInformation = function(options, callback) {
  1690. var self = this;
  1691. // Unpack calls
  1692. var args = Array.prototype.slice.call(arguments, 0);
  1693. callback = args.pop();
  1694. if(typeof callback != 'function') args.push(callback);
  1695. options = args.length ? args.shift() || {} : {};
  1696. // Execute using callback
  1697. if(typeof callback == 'function') return indexInformation(self, options, callback);
  1698. // Return a Promise
  1699. return new this.s.promiseLibrary(function(resolve, reject) {
  1700. indexInformation(self, options, function(err, r) {
  1701. if(err) return reject(err);
  1702. resolve(r);
  1703. });
  1704. });
  1705. }
  1706. var indexInformation = function(self, options, callback) {
  1707. self.s.db.indexInformation(self.s.name, options, callback);
  1708. }
  1709. define.classMethod('indexInformation', {callback: true, promise:true});
  1710. /**
  1711. * The callback format for results
  1712. * @callback Collection~countCallback
  1713. * @param {MongoError} error An error instance representing the error during the execution.
  1714. * @param {number} result The count of documents that matched the query.
  1715. */
  1716. /**
  1717. * Count number of matching documents in the db to a query.
  1718. * @method
  1719. * @param {object} query The query for the count.
  1720. * @param {object} [options=null] Optional settings.
  1721. * @param {boolean} [options.limit=null] The limit of documents to count.
  1722. * @param {boolean} [options.skip=null] The number of documents to skip for the count.
  1723. * @param {string} [options.hint=null] An index name hint for the query.
  1724. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  1725. * @param {number} [options.maxTimeMS=null] Number of miliseconds to wait before aborting the query.
  1726. * @param {Collection~countCallback} [callback] The command result callback
  1727. * @return {Promise} returns Promise if no callback passed
  1728. */
  1729. Collection.prototype.count = function(query, options, callback) {
  1730. var self = this;
  1731. var args = Array.prototype.slice.call(arguments, 0);
  1732. callback = args.pop();
  1733. if(typeof callback != 'function') args.push(callback);
  1734. var queryOption = args.length ? args.shift() || {} : {};
  1735. var optionsOption = args.length ? args.shift() || {} : {};
  1736. // Execute using callback
  1737. if(typeof callback == 'function') return count(self, queryOption, optionsOption, callback);
  1738. // Check if query is empty
  1739. query = query || {};
  1740. options = options || {};
  1741. // Return a Promise
  1742. return new this.s.promiseLibrary(function(resolve, reject) {
  1743. count(self, query, options, function(err, r) {
  1744. if(err) return reject(err);
  1745. resolve(r);
  1746. });
  1747. });
  1748. };
  1749. var count = function(self, query, options, callback) {
  1750. var skip = options.skip;
  1751. var limit = options.limit;
  1752. var hint = options.hint;
  1753. var maxTimeMS = options.maxTimeMS;
  1754. // Final query
  1755. var cmd = {
  1756. 'count': self.s.name, 'query': query
  1757. };
  1758. // Add limit, skip and maxTimeMS if defined
  1759. if(typeof skip == 'number') cmd.skip = skip;
  1760. if(typeof limit == 'number') cmd.limit = limit;
  1761. if(typeof maxTimeMS == 'number') cmd.maxTimeMS = maxTimeMS;
  1762. if(hint) options.hint = hint;
  1763. options = shallowClone(options);
  1764. // Ensure we have the right read preference inheritance
  1765. options = getReadPreference(self, options, self.s.db, self);
  1766. // Do we have a readConcern specified
  1767. if(self.s.readConcern) {
  1768. cmd.readConcern = self.s.readConcern;
  1769. }
  1770. // Have we specified collation
  1771. decorateWithCollation(cmd, self, options);
  1772. // Execute command
  1773. self.s.db.command(cmd, options, function(err, result) {
  1774. if(err) return handleCallback(callback, err);
  1775. handleCallback(callback, null, result.n);
  1776. });
  1777. }
  1778. define.classMethod('count', {callback: true, promise:true});
  1779. /**
  1780. * The distinct command returns returns a list of distinct values for the given key across a collection.
  1781. * @method
  1782. * @param {string} key Field of the document to find distinct values for.
  1783. * @param {object} query The query for filtering the set of documents to which we apply the distinct filter.
  1784. * @param {object} [options=null] Optional settings.
  1785. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  1786. * @param {number} [options.maxTimeMS=null] Number of miliseconds to wait before aborting the query.
  1787. * @param {Collection~resultCallback} [callback] The command result callback
  1788. * @return {Promise} returns Promise if no callback passed
  1789. */
  1790. Collection.prototype.distinct = function(key, query, options, callback) {
  1791. var self = this;
  1792. var args = Array.prototype.slice.call(arguments, 1);
  1793. callback = args.pop();
  1794. if(typeof callback != 'function') args.push(callback);
  1795. var queryOption = args.length ? args.shift() || {} : {};
  1796. var optionsOption = args.length ? args.shift() || {} : {};
  1797. // Execute using callback
  1798. if(typeof callback == 'function') return distinct(self, key, queryOption, optionsOption, callback);
  1799. // Ensure the query and options are set
  1800. query = query || {};
  1801. options = options || {};
  1802. // Return a Promise
  1803. return new this.s.promiseLibrary(function(resolve, reject) {
  1804. distinct(self, key, query, options, function(err, r) {
  1805. if(err) return reject(err);
  1806. resolve(r);
  1807. });
  1808. });
  1809. };
  1810. var distinct = function(self, key, query, options, callback) {
  1811. // maxTimeMS option
  1812. var maxTimeMS = options.maxTimeMS;
  1813. // Distinct command
  1814. var cmd = {
  1815. 'distinct': self.s.name, 'key': key, 'query': query
  1816. };
  1817. options = shallowClone(options);
  1818. // Ensure we have the right read preference inheritance
  1819. options = getReadPreference(self, options, self.s.db, self);
  1820. // Add maxTimeMS if defined
  1821. if(typeof maxTimeMS == 'number')
  1822. cmd.maxTimeMS = maxTimeMS;
  1823. // Do we have a readConcern specified
  1824. if(self.s.readConcern) {
  1825. cmd.readConcern = self.s.readConcern;
  1826. }
  1827. // Have we specified collation
  1828. decorateWithCollation(cmd, self, options);
  1829. // Execute the command
  1830. self.s.db.command(cmd, options, function(err, result) {
  1831. if(err) return handleCallback(callback, err);
  1832. handleCallback(callback, null, result.values);
  1833. });
  1834. }
  1835. define.classMethod('distinct', {callback: true, promise:true});
  1836. /**
  1837. * Retrieve all the indexes on the collection.
  1838. * @method
  1839. * @param {Collection~resultCallback} [callback] The command result callback
  1840. * @return {Promise} returns Promise if no callback passed
  1841. */
  1842. Collection.prototype.indexes = function(callback) {
  1843. var self = this;
  1844. // Execute using callback
  1845. if(typeof callback == 'function') return indexes(self, callback);
  1846. // Return a Promise
  1847. return new this.s.promiseLibrary(function(resolve, reject) {
  1848. indexes(self, function(err, r) {
  1849. if(err) return reject(err);
  1850. resolve(r);
  1851. });
  1852. });
  1853. }
  1854. var indexes = function(self, callback) {
  1855. self.s.db.indexInformation(self.s.name, {full:true}, callback);
  1856. }
  1857. define.classMethod('indexes', {callback: true, promise:true});
  1858. /**
  1859. * Get all the collection statistics.
  1860. *
  1861. * @method
  1862. * @param {object} [options=null] Optional settings.
  1863. * @param {number} [options.scale=null] Divide the returned sizes by scale value.
  1864. * @param {Collection~resultCallback} [callback] The collection result callback
  1865. * @return {Promise} returns Promise if no callback passed
  1866. */
  1867. Collection.prototype.stats = function(options, callback) {
  1868. var self = this;
  1869. var args = Array.prototype.slice.call(arguments, 0);
  1870. callback = args.pop();
  1871. if(typeof callback != 'function') args.push(callback);
  1872. // Fetch all commands
  1873. options = args.length ? args.shift() || {} : {};
  1874. // Execute using callback
  1875. if(typeof callback == 'function') return stats(self, options, callback);
  1876. // Return a Promise
  1877. return new this.s.promiseLibrary(function(resolve, reject) {
  1878. stats(self, options, function(err, r) {
  1879. if(err) return reject(err);
  1880. resolve(r);
  1881. });
  1882. });
  1883. }
  1884. var stats = function(self, options, callback) {
  1885. // Build command object
  1886. var commandObject = {
  1887. collStats:self.s.name
  1888. }
  1889. // Check if we have the scale value
  1890. if(options['scale'] != null) commandObject['scale'] = options['scale'];
  1891. options = shallowClone(options);
  1892. // Ensure we have the right read preference inheritance
  1893. options = getReadPreference(self, options, self.s.db, self);
  1894. // Execute the command
  1895. self.s.db.command(commandObject, options, callback);
  1896. }
  1897. define.classMethod('stats', {callback: true, promise:true});
  1898. /**
  1899. * @typedef {Object} Collection~findAndModifyWriteOpResult
  1900. * @property {object} value Document returned from findAndModify command.
  1901. * @property {object} lastErrorObject The raw lastErrorObject returned from the command.
  1902. * @property {Number} ok Is 1 if the command executed correctly.
  1903. */
  1904. /**
  1905. * The callback format for inserts
  1906. * @callback Collection~findAndModifyCallback
  1907. * @param {MongoError} error An error instance representing the error during the execution.
  1908. * @param {Collection~findAndModifyWriteOpResult} result The result object if the command was executed successfully.
  1909. */
  1910. /**
  1911. * Find a document and delete it in one atomic operation, requires a write lock for the duration of the operation.
  1912. *
  1913. * @method
  1914. * @param {object} filter Document selection filter.
  1915. * @param {object} [options=null] Optional settings.
  1916. * @param {object} [options.projection=null] Limits the fields to return for all matching documents.
  1917. * @param {object} [options.sort=null] Determines which document the operation modifies if the query selects multiple documents.
  1918. * @param {number} [options.maxTimeMS=null] The maximum amount of time to allow the query to run.
  1919. * @param {Collection~findAndModifyCallback} [callback] The collection result callback
  1920. * @return {Promise} returns Promise if no callback passed
  1921. */
  1922. Collection.prototype.findOneAndDelete = function(filter, options, callback) {
  1923. var self = this;
  1924. if(typeof options == 'function') callback = options, options = {};
  1925. options = options || {};
  1926. // Basic validation
  1927. if(filter == null || typeof filter != 'object') throw toError('filter parameter must be an object');
  1928. // Execute using callback
  1929. if(typeof callback == 'function') return findOneAndDelete(self, filter, options, callback);
  1930. // Return a Promise
  1931. return new this.s.promiseLibrary(function(resolve, reject) {
  1932. options = options || {};
  1933. findOneAndDelete(self, filter, options, function(err, r) {
  1934. if(err) return reject(err);
  1935. resolve(r);
  1936. });
  1937. });
  1938. }
  1939. var findOneAndDelete = function(self, filter, options, callback) {
  1940. // Final options
  1941. var finalOptions = shallowClone(options);
  1942. finalOptions['fields'] = options.projection;
  1943. finalOptions['remove'] = true;
  1944. // Execute find and Modify
  1945. self.findAndModify(
  1946. filter
  1947. , options.sort
  1948. , null
  1949. , finalOptions
  1950. , callback
  1951. );
  1952. }
  1953. define.classMethod('findOneAndDelete', {callback: true, promise:true});
  1954. /**
  1955. * Find a document and replace it in one atomic operation, requires a write lock for the duration of the operation.
  1956. *
  1957. * @method
  1958. * @param {object} filter Document selection filter.
  1959. * @param {object} replacement Document replacing the matching document.
  1960. * @param {object} [options=null] Optional settings.
  1961. * @param {object} [options.projection=null] Limits the fields to return for all matching documents.
  1962. * @param {object} [options.sort=null] Determines which document the operation modifies if the query selects multiple documents.
  1963. * @param {number} [options.maxTimeMS=null] The maximum amount of time to allow the query to run.
  1964. * @param {boolean} [options.upsert=false] Upsert the document if it does not exist.
  1965. * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true.
  1966. * @param {Collection~findAndModifyCallback} [callback] The collection result callback
  1967. * @return {Promise} returns Promise if no callback passed
  1968. */
  1969. Collection.prototype.findOneAndReplace = function(filter, replacement, options, callback) {
  1970. var self = this;
  1971. if(typeof options == 'function') callback = options, options = {};
  1972. options = options || {};
  1973. // Basic validation
  1974. if(filter == null || typeof filter != 'object') throw toError('filter parameter must be an object');
  1975. if(replacement == null || typeof replacement != 'object') throw toError('replacement parameter must be an object');
  1976. // Execute using callback
  1977. if(typeof callback == 'function') return findOneAndReplace(self, filter, replacement, options, callback);
  1978. // Return a Promise
  1979. return new this.s.promiseLibrary(function(resolve, reject) {
  1980. options = options || {};
  1981. findOneAndReplace(self, filter, replacement, options, function(err, r) {
  1982. if(err) return reject(err);
  1983. resolve(r);
  1984. });
  1985. });
  1986. }
  1987. var findOneAndReplace = function(self, filter, replacement, options, callback) {
  1988. // Final options
  1989. var finalOptions = shallowClone(options);
  1990. finalOptions['fields'] = options.projection;
  1991. finalOptions['update'] = true;
  1992. finalOptions['new'] = typeof options.returnOriginal == 'boolean' ? !options.returnOriginal : false;
  1993. finalOptions['upsert'] = typeof options.upsert == 'boolean' ? options.upsert : false;
  1994. // Execute findAndModify
  1995. self.findAndModify(
  1996. filter
  1997. , options.sort
  1998. , replacement
  1999. , finalOptions
  2000. , callback
  2001. );
  2002. }
  2003. define.classMethod('findOneAndReplace', {callback: true, promise:true});
  2004. /**
  2005. * Find a document and update it in one atomic operation, requires a write lock for the duration of the operation.
  2006. *
  2007. * @method
  2008. * @param {object} filter Document selection filter.
  2009. * @param {object} update Update operations to be performed on the document
  2010. * @param {object} [options=null] Optional settings.
  2011. * @param {object} [options.projection=null] Limits the fields to return for all matching documents.
  2012. * @param {object} [options.sort=null] Determines which document the operation modifies if the query selects multiple documents.
  2013. * @param {number} [options.maxTimeMS=null] The maximum amount of time to allow the query to run.
  2014. * @param {boolean} [options.upsert=false] Upsert the document if it does not exist.
  2015. * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true.
  2016. * @param {Collection~findAndModifyCallback} [callback] The collection result callback
  2017. * @return {Promise} returns Promise if no callback passed
  2018. */
  2019. Collection.prototype.findOneAndUpdate = function(filter, update, options, callback) {
  2020. var self = this;
  2021. if(typeof options == 'function') callback = options, options = {};
  2022. options = options || {};
  2023. // Basic validation
  2024. if(filter == null || typeof filter != 'object') throw toError('filter parameter must be an object');
  2025. if(update == null || typeof update != 'object') throw toError('update parameter must be an object');
  2026. // Execute using callback
  2027. if(typeof callback == 'function') return findOneAndUpdate(self, filter, update, options, callback);
  2028. // Return a Promise
  2029. return new this.s.promiseLibrary(function(resolve, reject) {
  2030. options = options || {};
  2031. findOneAndUpdate(self, filter, update, options, function(err, r) {
  2032. if(err) return reject(err);
  2033. resolve(r);
  2034. });
  2035. });
  2036. }
  2037. var findOneAndUpdate = function(self, filter, update, options, callback) {
  2038. // Final options
  2039. var finalOptions = shallowClone(options);
  2040. finalOptions['fields'] = options.projection;
  2041. finalOptions['update'] = true;
  2042. finalOptions['new'] = typeof options.returnOriginal == 'boolean' ? !options.returnOriginal : false;
  2043. finalOptions['upsert'] = typeof options.upsert == 'boolean' ? options.upsert : false;
  2044. // Execute findAndModify
  2045. self.findAndModify(
  2046. filter
  2047. , options.sort
  2048. , update
  2049. , finalOptions
  2050. , callback
  2051. );
  2052. }
  2053. define.classMethod('findOneAndUpdate', {callback: true, promise:true});
  2054. /**
  2055. * Find and update a document.
  2056. * @method
  2057. * @param {object} query Query object to locate the object to modify.
  2058. * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate.
  2059. * @param {object} doc The fields/vals to be updated.
  2060. * @param {object} [options=null] Optional settings.
  2061. * @param {(number|string)} [options.w=null] The write concern.
  2062. * @param {number} [options.wtimeout=null] The write concern timeout.
  2063. * @param {boolean} [options.j=false] Specify a journal write concern.
  2064. * @param {boolean} [options.remove=false] Set to true to remove the object before returning.
  2065. * @param {boolean} [options.upsert=false] Perform an upsert operation.
  2066. * @param {boolean} [options.new=false] Set to true if you want to return the modified object rather than the original. Ignored for remove.
  2067. * @param {object} [options.fields=null] Object containing the field projection for the result returned from the operation.
  2068. * @param {Collection~findAndModifyCallback} [callback] The command result callback
  2069. * @return {Promise} returns Promise if no callback passed
  2070. * @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead
  2071. */
  2072. Collection.prototype.findAndModify = function(query, sort, doc, options, callback) {
  2073. var self = this;
  2074. var args = Array.prototype.slice.call(arguments, 1);
  2075. callback = args.pop();
  2076. if(typeof callback != 'function') args.push(callback);
  2077. sort = args.length ? args.shift() || [] : [];
  2078. doc = args.length ? args.shift() : null;
  2079. options = args.length ? args.shift() || {} : {};
  2080. // Clone options
  2081. options = shallowClone(options);
  2082. // Force read preference primary
  2083. options.readPreference = ReadPreference.PRIMARY;
  2084. // Execute using callback
  2085. if(typeof callback == 'function') return findAndModify(self, query, sort, doc, options, callback);
  2086. // Return a Promise
  2087. return new this.s.promiseLibrary(function(resolve, reject) {
  2088. options = options || {};
  2089. findAndModify(self, query, sort, doc, options, function(err, r) {
  2090. if(err) return reject(err);
  2091. resolve(r);
  2092. });
  2093. });
  2094. }
  2095. var findAndModify = function(self, query, sort, doc, options, callback) {
  2096. // Create findAndModify command object
  2097. var queryObject = {
  2098. 'findandmodify': self.s.name
  2099. , 'query': query
  2100. };
  2101. sort = formattedOrderClause(sort);
  2102. if(sort) {
  2103. queryObject.sort = sort;
  2104. }
  2105. queryObject.new = options.new ? true : false;
  2106. queryObject.remove = options.remove ? true : false;
  2107. queryObject.upsert = options.upsert ? true : false;
  2108. if(options.fields) {
  2109. queryObject.fields = options.fields;
  2110. }
  2111. if(doc && !options.remove) {
  2112. queryObject.update = doc;
  2113. }
  2114. if(options.maxTimeMS)
  2115. queryObject.maxTimeMS = options.maxTimeMS;
  2116. // Either use override on the function, or go back to default on either the collection
  2117. // level or db
  2118. if(options['serializeFunctions'] != null) {
  2119. options['serializeFunctions'] = options['serializeFunctions'];
  2120. } else {
  2121. options['serializeFunctions'] = self.s.serializeFunctions;
  2122. }
  2123. // No check on the documents
  2124. options.checkKeys = false;
  2125. // Get the write concern settings
  2126. var finalOptions = writeConcern(options, self.s.db, self, options);
  2127. // Decorate the findAndModify command with the write Concern
  2128. if(finalOptions.writeConcern) {
  2129. queryObject.writeConcern = finalOptions.writeConcern;
  2130. }
  2131. // Have we specified bypassDocumentValidation
  2132. if(typeof finalOptions.bypassDocumentValidation == 'boolean') {
  2133. queryObject.bypassDocumentValidation = finalOptions.bypassDocumentValidation;
  2134. }
  2135. // Have we specified collation
  2136. decorateWithCollation(queryObject, self, options);
  2137. // Execute the command
  2138. self.s.db.command(queryObject
  2139. , options, function(err, result) {
  2140. if(err) return handleCallback(callback, err, null);
  2141. return handleCallback(callback, null, result);
  2142. });
  2143. }
  2144. define.classMethod('findAndModify', {callback: true, promise:true});
  2145. /**
  2146. * Find and remove a document.
  2147. * @method
  2148. * @param {object} query Query object to locate the object to modify.
  2149. * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate.
  2150. * @param {object} [options=null] Optional settings.
  2151. * @param {(number|string)} [options.w=null] The write concern.
  2152. * @param {number} [options.wtimeout=null] The write concern timeout.
  2153. * @param {boolean} [options.j=false] Specify a journal write concern.
  2154. * @param {Collection~resultCallback} [callback] The command result callback
  2155. * @return {Promise} returns Promise if no callback passed
  2156. * @deprecated use findOneAndDelete instead
  2157. */
  2158. Collection.prototype.findAndRemove = function(query, sort, options, callback) {
  2159. var self = this;
  2160. var args = Array.prototype.slice.call(arguments, 1);
  2161. callback = args.pop();
  2162. if(typeof callback != 'function') args.push(callback);
  2163. sort = args.length ? args.shift() || [] : [];
  2164. options = args.length ? args.shift() || {} : {};
  2165. // Execute using callback
  2166. if(typeof callback == 'function') return findAndRemove(self, query, sort, options, callback);
  2167. // Return a Promise
  2168. return new this.s.promiseLibrary(function(resolve, reject) {
  2169. findAndRemove(self, query, sort, options, function(err, r) {
  2170. if(err) return reject(err);
  2171. resolve(r);
  2172. });
  2173. });
  2174. }
  2175. var findAndRemove = function(self, query, sort, options, callback) {
  2176. // Add the remove option
  2177. options['remove'] = true;
  2178. // Execute the callback
  2179. self.findAndModify(query, sort, null, options, callback);
  2180. }
  2181. define.classMethod('findAndRemove', {callback: true, promise:true});
  2182. function decorateWithWriteConcern(command, self, options) {
  2183. // Do we support collation 3.4 and higher
  2184. var capabilities = self.s.topology.capabilities();
  2185. // Do we support write concerns 3.4 and higher
  2186. if(capabilities && capabilities.commandsTakeWriteConcern) {
  2187. // Get the write concern settings
  2188. var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options);
  2189. // Add the write concern to the command
  2190. if(finalOptions.writeConcern) {
  2191. command.writeConcern = finalOptions.writeConcern;
  2192. }
  2193. }
  2194. }
  2195. function decorateWithCollation(command, self, options) {
  2196. // Do we support collation 3.4 and higher
  2197. var capabilities = self.s.topology.capabilities();
  2198. // Do we support write concerns 3.4 and higher
  2199. if(capabilities && capabilities.commandsTakeCollation) {
  2200. if(options.collation && typeof options.collation == 'object') {
  2201. command.collation = options.collation;
  2202. }
  2203. }
  2204. }
  2205. /**
  2206. * Execute an aggregation framework pipeline against the collection, needs MongoDB >= 2.2
  2207. * @method
  2208. * @param {object} pipeline Array containing all the aggregation framework commands for the execution.
  2209. * @param {object} [options=null] Optional settings.
  2210. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  2211. * @param {object} [options.cursor=null] Return the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor.
  2212. * @param {number} [options.cursor.batchSize=null] The batchSize for the cursor
  2213. * @param {boolean} [options.explain=false] Explain returns the aggregation execution plan (requires mongodb 2.6 >).
  2214. * @param {boolean} [options.allowDiskUse=false] allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >).
  2215. * @param {number} [options.maxTimeMS=null] maxTimeMS specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point.
  2216. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
  2217. * @param {boolean} [options.raw=false] Return document results as raw BSON buffers.
  2218. * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution.
  2219. * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types.
  2220. * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers.
  2221. * @param {object} [options.collation=null] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
  2222. * @param {Collection~resultCallback} callback The command result callback
  2223. * @return {(null|AggregationCursor)}
  2224. */
  2225. Collection.prototype.aggregate = function(pipeline, options, callback) {
  2226. var self = this;
  2227. if(Array.isArray(pipeline)) {
  2228. // Set up callback if one is provided
  2229. if(typeof options == 'function') {
  2230. callback = options;
  2231. options = {};
  2232. }
  2233. // If we have no options or callback we are doing
  2234. // a cursor based aggregation
  2235. if(options == null && callback == null) {
  2236. options = {};
  2237. }
  2238. } else {
  2239. // Aggregation pipeline passed as arguments on the method
  2240. var args = Array.prototype.slice.call(arguments, 0);
  2241. // Get the callback
  2242. callback = args.pop();
  2243. // Get the possible options object
  2244. var opts = args[args.length - 1];
  2245. // If it contains any of the admissible options pop it of the args
  2246. options = opts && (opts.readPreference
  2247. || opts.explain || opts.cursor || opts.out
  2248. || opts.maxTimeMS || opts.allowDiskUse) ? args.pop() : {};
  2249. // Left over arguments is the pipeline
  2250. pipeline = args;
  2251. }
  2252. // Ignore readConcern option
  2253. var ignoreReadConcern = false;
  2254. // Build the command
  2255. var command = { aggregate : this.s.name, pipeline : pipeline};
  2256. // If out was specified
  2257. if(typeof options.out == 'string') {
  2258. pipeline.push({$out: options.out});
  2259. // Ignore read concern
  2260. ignoreReadConcern = true;
  2261. } else if(pipeline.length > 0 && pipeline[pipeline.length - 1]['$out']) {
  2262. ignoreReadConcern = true;
  2263. }
  2264. // Decorate command with writeConcern if out has been specified
  2265. if(pipeline.length > 0 && pipeline[pipeline.length - 1]['$out']) {
  2266. decorateWithWriteConcern(command, self, options);
  2267. }
  2268. // Have we specified collation
  2269. decorateWithCollation(command, self, options);
  2270. // If we have bypassDocumentValidation set
  2271. if(typeof options.bypassDocumentValidation == 'boolean') {
  2272. command.bypassDocumentValidation = options.bypassDocumentValidation;
  2273. }
  2274. // Do we have a readConcern specified
  2275. if(!ignoreReadConcern && this.s.readConcern) {
  2276. command.readConcern = this.s.readConcern;
  2277. }
  2278. // If we have allowDiskUse defined
  2279. if(options.allowDiskUse) command.allowDiskUse = options.allowDiskUse;
  2280. if(typeof options.maxTimeMS == 'number') command.maxTimeMS = options.maxTimeMS;
  2281. options = shallowClone(options);
  2282. // Ensure we have the right read preference inheritance
  2283. options = getReadPreference(this, options, this.s.db, this);
  2284. // If explain has been specified add it
  2285. if(options.explain) command.explain = options.explain;
  2286. // Validate that cursor options is valid
  2287. if(options.cursor != null && typeof options.cursor != 'object') {
  2288. throw toError('cursor options must be an object');
  2289. }
  2290. // promiseLibrary
  2291. options.promiseLibrary = this.s.promiseLibrary;
  2292. // Set the AggregationCursor constructor
  2293. options.cursorFactory = AggregationCursor;
  2294. if(typeof callback != 'function') {
  2295. if(!this.s.topology.capabilities()) {
  2296. throw new MongoError('cannot connect to server');
  2297. }
  2298. if(this.s.topology.capabilities().hasAggregationCursor) {
  2299. options.cursor = options.cursor || { batchSize : 1000 };
  2300. command.cursor = options.cursor;
  2301. }
  2302. // Allow disk usage command
  2303. if(typeof options.allowDiskUse == 'boolean') command.allowDiskUse = options.allowDiskUse;
  2304. if(typeof options.maxTimeMS == 'number') command.maxTimeMS = options.maxTimeMS;
  2305. // Execute the cursor
  2306. return this.s.topology.cursor(this.s.namespace, command, options);
  2307. }
  2308. // We do not allow cursor
  2309. if(options.cursor) {
  2310. return this.s.topology.cursor(this.s.namespace, command, options);
  2311. }
  2312. // Execute the command
  2313. this.s.db.command(command, options, function(err, result) {
  2314. if(err) {
  2315. handleCallback(callback, err);
  2316. } else if(result['err'] || result['errmsg']) {
  2317. handleCallback(callback, toError(result));
  2318. } else if(typeof result == 'object' && result['serverPipeline']) {
  2319. handleCallback(callback, null, result['serverPipeline']);
  2320. } else if(typeof result == 'object' && result['stages']) {
  2321. handleCallback(callback, null, result['stages']);
  2322. } else {
  2323. handleCallback(callback, null, result.result);
  2324. }
  2325. });
  2326. }
  2327. define.classMethod('aggregate', {callback: true, promise:false});
  2328. /**
  2329. * The callback format for results
  2330. * @callback Collection~parallelCollectionScanCallback
  2331. * @param {MongoError} error An error instance representing the error during the execution.
  2332. * @param {Cursor[]} cursors A list of cursors returned allowing for parallel reading of collection.
  2333. */
  2334. /**
  2335. * Return N number of parallel cursors for a collection allowing parallel reading of entire collection. There are
  2336. * no ordering guarantees for returned results.
  2337. * @method
  2338. * @param {object} [options=null] Optional settings.
  2339. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  2340. * @param {number} [options.batchSize=null] Set the batchSize for the getMoreCommand when iterating over the query results.
  2341. * @param {number} [options.numCursors=1] The maximum number of parallel command cursors to return (the number of returned cursors will be in the range 1:numCursors)
  2342. * @param {boolean} [options.raw=false] Return all BSON documents as Raw Buffer documents.
  2343. * @param {Collection~parallelCollectionScanCallback} [callback] The command result callback
  2344. * @return {Promise} returns Promise if no callback passed
  2345. */
  2346. Collection.prototype.parallelCollectionScan = function(options, callback) {
  2347. var self = this;
  2348. if(typeof options == 'function') callback = options, options = {numCursors: 1};
  2349. // Set number of cursors to 1
  2350. options.numCursors = options.numCursors || 1;
  2351. options.batchSize = options.batchSize || 1000;
  2352. options = shallowClone(options);
  2353. // Ensure we have the right read preference inheritance
  2354. options = getReadPreference(this, options, this.s.db, this);
  2355. // Add a promiseLibrary
  2356. options.promiseLibrary = this.s.promiseLibrary;
  2357. // Execute using callback
  2358. if(typeof callback == 'function') return parallelCollectionScan(self, options, callback);
  2359. // Return a Promise
  2360. return new this.s.promiseLibrary(function(resolve, reject) {
  2361. parallelCollectionScan(self, options, function(err, r) {
  2362. if(err) return reject(err);
  2363. resolve(r);
  2364. });
  2365. });
  2366. }
  2367. var parallelCollectionScan = function(self, options, callback) {
  2368. // Create command object
  2369. var commandObject = {
  2370. parallelCollectionScan: self.s.name
  2371. , numCursors: options.numCursors
  2372. }
  2373. // Do we have a readConcern specified
  2374. if(self.s.readConcern) {
  2375. commandObject.readConcern = self.s.readConcern;
  2376. }
  2377. // Store the raw value
  2378. var raw = options.raw;
  2379. delete options['raw'];
  2380. // Execute the command
  2381. self.s.db.command(commandObject, options, function(err, result) {
  2382. if(err) return handleCallback(callback, err, null);
  2383. if(result == null) return handleCallback(callback, new Error("no result returned for parallelCollectionScan"), null);
  2384. var cursors = [];
  2385. // Add the raw back to the option
  2386. if(raw) options.raw = raw;
  2387. // Create command cursors for each item
  2388. for(var i = 0; i < result.cursors.length; i++) {
  2389. var rawId = result.cursors[i].cursor.id
  2390. // Convert cursorId to Long if needed
  2391. var cursorId = typeof rawId == 'number' ? Long.fromNumber(rawId) : rawId;
  2392. // Add a command cursor
  2393. cursors.push(self.s.topology.cursor(self.s.namespace, cursorId, options));
  2394. }
  2395. handleCallback(callback, null, cursors);
  2396. });
  2397. }
  2398. define.classMethod('parallelCollectionScan', {callback: true, promise:true});
  2399. /**
  2400. * Execute the geoNear command to search for items in the collection
  2401. *
  2402. * @method
  2403. * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order.
  2404. * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order.
  2405. * @param {object} [options=null] Optional settings.
  2406. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  2407. * @param {number} [options.num=null] Max number of results to return.
  2408. * @param {number} [options.minDistance=null] Include results starting at minDistance from a point (2.6 or higher)
  2409. * @param {number} [options.maxDistance=null] Include results up to maxDistance from the point.
  2410. * @param {number} [options.distanceMultiplier=null] Include a value to multiply the distances with allowing for range conversions.
  2411. * @param {object} [options.query=null] Filter the results by a query.
  2412. * @param {boolean} [options.spherical=false] Perform query using a spherical model.
  2413. * @param {boolean} [options.uniqueDocs=false] The closest location in a document to the center of the search region will always be returned MongoDB > 2.X.
  2414. * @param {boolean} [options.includeLocs=false] Include the location data fields in the top level of the results MongoDB > 2.X.
  2415. * @param {Collection~resultCallback} [callback] The command result callback
  2416. * @return {Promise} returns Promise if no callback passed
  2417. */
  2418. Collection.prototype.geoNear = function(x, y, options, callback) {
  2419. var self = this;
  2420. var point = typeof(x) == 'object' && x
  2421. , args = Array.prototype.slice.call(arguments, point?1:2);
  2422. callback = args.pop();
  2423. if(typeof callback != 'function') args.push(callback);
  2424. // Fetch all commands
  2425. options = args.length ? args.shift() || {} : {};
  2426. // Execute using callback
  2427. if(typeof callback == 'function') return geoNear(self, x, y, point, options, callback);
  2428. // Return a Promise
  2429. return new this.s.promiseLibrary(function(resolve, reject) {
  2430. geoNear(self, x, y, point, options, function(err, r) {
  2431. if(err) return reject(err);
  2432. resolve(r);
  2433. });
  2434. });
  2435. }
  2436. var geoNear = function(self, x, y, point, options, callback) {
  2437. // Build command object
  2438. var commandObject = {
  2439. geoNear:self.s.name,
  2440. near: point || [x, y]
  2441. }
  2442. options = shallowClone(options);
  2443. // Ensure we have the right read preference inheritance
  2444. options = getReadPreference(self, options, self.s.db, self);
  2445. // Exclude readPreference and existing options to prevent user from
  2446. // shooting themselves in the foot
  2447. var exclude = {
  2448. readPreference: true,
  2449. geoNear: true,
  2450. near: true
  2451. };
  2452. // Filter out any excluded objects
  2453. commandObject = decorateCommand(commandObject, options, exclude);
  2454. // Do we have a readConcern specified
  2455. if(self.s.readConcern) {
  2456. commandObject.readConcern = self.s.readConcern;
  2457. }
  2458. // Have we specified collation
  2459. decorateWithCollation(commandObject, self, options);
  2460. // Execute the command
  2461. self.s.db.command(commandObject, options, function (err, res) {
  2462. if(err) return handleCallback(callback, err);
  2463. if(res.err || res.errmsg) return handleCallback(callback, toError(res));
  2464. // should we only be returning res.results here? Not sure if the user
  2465. // should see the other return information
  2466. handleCallback(callback, null, res);
  2467. });
  2468. }
  2469. define.classMethod('geoNear', {callback: true, promise:true});
  2470. /**
  2471. * Execute a geo search using a geo haystack index on a collection.
  2472. *
  2473. * @method
  2474. * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order.
  2475. * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order.
  2476. * @param {object} [options=null] Optional settings.
  2477. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  2478. * @param {number} [options.maxDistance=null] Include results up to maxDistance from the point.
  2479. * @param {object} [options.search=null] Filter the results by a query.
  2480. * @param {number} [options.limit=false] Max number of results to return.
  2481. * @param {Collection~resultCallback} [callback] The command result callback
  2482. * @return {Promise} returns Promise if no callback passed
  2483. */
  2484. Collection.prototype.geoHaystackSearch = function(x, y, options, callback) {
  2485. var self = this;
  2486. var args = Array.prototype.slice.call(arguments, 2);
  2487. callback = args.pop();
  2488. if(typeof callback != 'function') args.push(callback);
  2489. // Fetch all commands
  2490. options = args.length ? args.shift() || {} : {};
  2491. // Execute using callback
  2492. if(typeof callback == 'function') return geoHaystackSearch(self, x, y, options, callback);
  2493. // Return a Promise
  2494. return new this.s.promiseLibrary(function(resolve, reject) {
  2495. geoHaystackSearch(self, x, y, options, function(err, r) {
  2496. if(err) return reject(err);
  2497. resolve(r);
  2498. });
  2499. });
  2500. }
  2501. var geoHaystackSearch = function(self, x, y, options, callback) {
  2502. // Build command object
  2503. var commandObject = {
  2504. geoSearch: self.s.name,
  2505. near: [x, y]
  2506. }
  2507. // Remove read preference from hash if it exists
  2508. commandObject = decorateCommand(commandObject, options, {readPreference: true});
  2509. options = shallowClone(options);
  2510. // Ensure we have the right read preference inheritance
  2511. options = getReadPreference(self, options, self.s.db, self);
  2512. // Do we have a readConcern specified
  2513. if(self.s.readConcern) {
  2514. commandObject.readConcern = self.s.readConcern;
  2515. }
  2516. // Execute the command
  2517. self.s.db.command(commandObject, options, function (err, res) {
  2518. if(err) return handleCallback(callback, err);
  2519. if(res.err || res.errmsg) handleCallback(callback, toError(res));
  2520. // should we only be returning res.results here? Not sure if the user
  2521. // should see the other return information
  2522. handleCallback(callback, null, res);
  2523. });
  2524. }
  2525. define.classMethod('geoHaystackSearch', {callback: true, promise:true});
  2526. /**
  2527. * Group function helper
  2528. * @ignore
  2529. */
  2530. // var groupFunction = function () {
  2531. // var c = db[ns].find(condition);
  2532. // var map = new Map();
  2533. // var reduce_function = reduce;
  2534. //
  2535. // while (c.hasNext()) {
  2536. // var obj = c.next();
  2537. // var key = {};
  2538. //
  2539. // for (var i = 0, len = keys.length; i < len; ++i) {
  2540. // var k = keys[i];
  2541. // key[k] = obj[k];
  2542. // }
  2543. //
  2544. // var aggObj = map.get(key);
  2545. //
  2546. // if (aggObj == null) {
  2547. // var newObj = Object.extend({}, key);
  2548. // aggObj = Object.extend(newObj, initial);
  2549. // map.put(key, aggObj);
  2550. // }
  2551. //
  2552. // reduce_function(obj, aggObj);
  2553. // }
  2554. //
  2555. // return { "result": map.values() };
  2556. // }.toString();
  2557. var groupFunction = 'function () {\nvar c = db[ns].find(condition);\nvar map = new Map();\nvar reduce_function = reduce;\n\nwhile (c.hasNext()) {\nvar obj = c.next();\nvar key = {};\n\nfor (var i = 0, len = keys.length; i < len; ++i) {\nvar k = keys[i];\nkey[k] = obj[k];\n}\n\nvar aggObj = map.get(key);\n\nif (aggObj == null) {\nvar newObj = Object.extend({}, key);\naggObj = Object.extend(newObj, initial);\nmap.put(key, aggObj);\n}\n\nreduce_function(obj, aggObj);\n}\n\nreturn { "result": map.values() };\n}';
  2558. /**
  2559. * Run a group command across a collection
  2560. *
  2561. * @method
  2562. * @param {(object|array|function|code)} keys An object, array or function expressing the keys to group by.
  2563. * @param {object} condition An optional condition that must be true for a row to be considered.
  2564. * @param {object} initial Initial value of the aggregation counter object.
  2565. * @param {(function|Code)} reduce The reduce function aggregates (reduces) the objects iterated
  2566. * @param {(function|Code)} finalize An optional function to be run on each item in the result set just before the item is returned.
  2567. * @param {boolean} command Specify if you wish to run using the internal group command or using eval, default is true.
  2568. * @param {object} [options=null] Optional settings.
  2569. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  2570. * @param {Collection~resultCallback} [callback] The command result callback
  2571. * @return {Promise} returns Promise if no callback passed
  2572. */
  2573. Collection.prototype.group = function(keys, condition, initial, reduce, finalize, command, options, callback) {
  2574. var self = this;
  2575. var args = Array.prototype.slice.call(arguments, 3);
  2576. callback = args.pop();
  2577. if(typeof callback != 'function') args.push(callback);
  2578. // Fetch all commands
  2579. reduce = args.length ? args.shift() : null;
  2580. finalize = args.length ? args.shift() : null;
  2581. command = args.length ? args.shift() : null;
  2582. options = args.length ? args.shift() || {} : {};
  2583. // Make sure we are backward compatible
  2584. if(!(typeof finalize == 'function')) {
  2585. command = finalize;
  2586. finalize = null;
  2587. }
  2588. if (!Array.isArray(keys) && keys instanceof Object && typeof(keys) !== 'function' && !(keys._bsontype == 'Code')) {
  2589. keys = Object.keys(keys);
  2590. }
  2591. if(typeof reduce === 'function') {
  2592. reduce = reduce.toString();
  2593. }
  2594. if(typeof finalize === 'function') {
  2595. finalize = finalize.toString();
  2596. }
  2597. // Set up the command as default
  2598. command = command == null ? true : command;
  2599. // Execute using callback
  2600. if(typeof callback == 'function') return group(self, keys, condition, initial, reduce, finalize, command, options, callback);
  2601. // Return a Promise
  2602. return new this.s.promiseLibrary(function(resolve, reject) {
  2603. group(self, keys, condition, initial, reduce, finalize, command, options, function(err, r) {
  2604. if(err) return reject(err);
  2605. resolve(r);
  2606. });
  2607. });
  2608. }
  2609. var group = function(self, keys, condition, initial, reduce, finalize, command, options, callback) {
  2610. // Execute using the command
  2611. if(command) {
  2612. var reduceFunction = reduce && reduce._bsontype == 'Code'
  2613. ? reduce
  2614. : new Code(reduce);
  2615. var selector = {
  2616. group: {
  2617. 'ns': self.s.name
  2618. , '$reduce': reduceFunction
  2619. , 'cond': condition
  2620. , 'initial': initial
  2621. , 'out': "inline"
  2622. }
  2623. };
  2624. // if finalize is defined
  2625. if(finalize != null) selector.group['finalize'] = finalize;
  2626. // Set up group selector
  2627. if ('function' === typeof keys || (keys && keys._bsontype == 'Code')) {
  2628. selector.group.$keyf = keys && keys._bsontype == 'Code'
  2629. ? keys
  2630. : new Code(keys);
  2631. } else {
  2632. var hash = {};
  2633. keys.forEach(function (key) {
  2634. hash[key] = 1;
  2635. });
  2636. selector.group.key = hash;
  2637. }
  2638. options = shallowClone(options);
  2639. // Ensure we have the right read preference inheritance
  2640. options = getReadPreference(self, options, self.s.db, self);
  2641. // Do we have a readConcern specified
  2642. if(self.s.readConcern) {
  2643. selector.readConcern = self.s.readConcern;
  2644. }
  2645. // Have we specified collation
  2646. decorateWithCollation(selector, self, options);
  2647. // Execute command
  2648. self.s.db.command(selector, options, function(err, result) {
  2649. if(err) return handleCallback(callback, err, null);
  2650. handleCallback(callback, null, result.retval);
  2651. });
  2652. } else {
  2653. // Create execution scope
  2654. var scope = reduce != null && reduce._bsontype == 'Code'
  2655. ? reduce.scope
  2656. : {};
  2657. scope.ns = self.s.name;
  2658. scope.keys = keys;
  2659. scope.condition = condition;
  2660. scope.initial = initial;
  2661. // Pass in the function text to execute within mongodb.
  2662. var groupfn = groupFunction.replace(/ reduce;/, reduce.toString() + ';');
  2663. self.s.db.eval(new Code(groupfn, scope), function (err, results) {
  2664. if (err) return handleCallback(callback, err, null);
  2665. handleCallback(callback, null, results.result || results);
  2666. });
  2667. }
  2668. }
  2669. define.classMethod('group', {callback: true, promise:true});
  2670. /**
  2671. * Functions that are passed as scope args must
  2672. * be converted to Code instances.
  2673. * @ignore
  2674. */
  2675. function processScope (scope) {
  2676. if(!isObject(scope) || scope._bsontype == 'ObjectID') {
  2677. return scope;
  2678. }
  2679. var keys = Object.keys(scope);
  2680. var i = keys.length;
  2681. var key;
  2682. var new_scope = {};
  2683. while (i--) {
  2684. key = keys[i];
  2685. if ('function' == typeof scope[key]) {
  2686. new_scope[key] = new Code(String(scope[key]));
  2687. } else {
  2688. new_scope[key] = processScope(scope[key]);
  2689. }
  2690. }
  2691. return new_scope;
  2692. }
  2693. /**
  2694. * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection.
  2695. *
  2696. * @method
  2697. * @param {(function|string)} map The mapping function.
  2698. * @param {(function|string)} reduce The reduce function.
  2699. * @param {object} [options=null] Optional settings.
  2700. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  2701. * @param {object} [options.out=null] Sets the output target for the map reduce job. *{inline:1} | {replace:'collectionName'} | {merge:'collectionName'} | {reduce:'collectionName'}*
  2702. * @param {object} [options.query=null] Query filter object.
  2703. * @param {object} [options.sort=null] Sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces.
  2704. * @param {number} [options.limit=null] Number of objects to return from collection.
  2705. * @param {boolean} [options.keeptemp=false] Keep temporary data.
  2706. * @param {(function|string)} [options.finalize=null] Finalize function.
  2707. * @param {object} [options.scope=null] Can pass in variables that can be access from map/reduce/finalize.
  2708. * @param {boolean} [options.jsMode=false] It is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X.
  2709. * @param {boolean} [options.verbose=false] Provide statistics on job execution time.
  2710. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
  2711. * @param {Collection~resultCallback} [callback] The command result callback
  2712. * @throws {MongoError}
  2713. * @return {Promise} returns Promise if no callback passed
  2714. */
  2715. Collection.prototype.mapReduce = function(map, reduce, options, callback) {
  2716. var self = this;
  2717. if('function' === typeof options) callback = options, options = {};
  2718. // Out must allways be defined (make sure we don't break weirdly on pre 1.8+ servers)
  2719. if(null == options.out) {
  2720. throw new Error("the out option parameter must be defined, see mongodb docs for possible values");
  2721. }
  2722. if('function' === typeof map) {
  2723. map = map.toString();
  2724. }
  2725. if('function' === typeof reduce) {
  2726. reduce = reduce.toString();
  2727. }
  2728. if('function' === typeof options.finalize) {
  2729. options.finalize = options.finalize.toString();
  2730. }
  2731. // Execute using callback
  2732. if(typeof callback == 'function') return mapReduce(self, map, reduce, options, callback);
  2733. // Return a Promise
  2734. return new this.s.promiseLibrary(function(resolve, reject) {
  2735. mapReduce(self, map, reduce, options, function(err, r, r1) {
  2736. if(err) return reject(err);
  2737. if(!r1) return resolve(r);
  2738. resolve({results: r, stats: r1});
  2739. });
  2740. });
  2741. }
  2742. var mapReduce = function(self, map, reduce, options, callback) {
  2743. var mapCommandHash = {
  2744. mapreduce: self.s.name
  2745. , map: map
  2746. , reduce: reduce
  2747. };
  2748. // Add any other options passed in
  2749. for(var n in options) {
  2750. if('scope' == n) {
  2751. mapCommandHash[n] = processScope(options[n]);
  2752. } else {
  2753. mapCommandHash[n] = options[n];
  2754. }
  2755. }
  2756. options = shallowClone(options);
  2757. // Ensure we have the right read preference inheritance
  2758. options = getReadPreference(self, options, self.s.db, self);
  2759. // If we have a read preference and inline is not set as output fail hard
  2760. if((options.readPreference != false && options.readPreference != 'primary')
  2761. && options['out'] && (options['out'].inline != 1 && options['out'] != 'inline')) {
  2762. // Force readPreference to primary
  2763. options.readPreference = 'primary';
  2764. // Decorate command with writeConcern if supported
  2765. decorateWithWriteConcern(mapCommandHash, self, options);
  2766. } else if(self.s.readConcern) {
  2767. mapCommandHash.readConcern = self.s.readConcern;
  2768. }
  2769. // Is bypassDocumentValidation specified
  2770. if(typeof options.bypassDocumentValidation == 'boolean') {
  2771. mapCommandHash.bypassDocumentValidation = options.bypassDocumentValidation;
  2772. }
  2773. // Have we specified collation
  2774. decorateWithCollation(mapCommandHash, self, options);
  2775. // Execute command
  2776. self.s.db.command(mapCommandHash, {readPreference:options.readPreference}, function (err, result) {
  2777. if(err) return handleCallback(callback, err);
  2778. // Check if we have an error
  2779. if(1 != result.ok || result.err || result.errmsg) {
  2780. return handleCallback(callback, toError(result));
  2781. }
  2782. // Create statistics value
  2783. var stats = {};
  2784. if(result.timeMillis) stats['processtime'] = result.timeMillis;
  2785. if(result.counts) stats['counts'] = result.counts;
  2786. if(result.timing) stats['timing'] = result.timing;
  2787. // invoked with inline?
  2788. if(result.results) {
  2789. // If we wish for no verbosity
  2790. if(options['verbose'] == null || !options['verbose']) {
  2791. return handleCallback(callback, null, result.results);
  2792. }
  2793. return handleCallback(callback, null, result.results, stats);
  2794. }
  2795. // The returned collection
  2796. var collection = null;
  2797. // If we have an object it's a different db
  2798. if(result.result != null && typeof result.result == 'object') {
  2799. var doc = result.result;
  2800. collection = self.s.db.db(doc.db).collection(doc.collection);
  2801. } else {
  2802. // Create a collection object that wraps the result collection
  2803. collection = self.s.db.collection(result.result)
  2804. }
  2805. // If we wish for no verbosity
  2806. if(options['verbose'] == null || !options['verbose']) {
  2807. return handleCallback(callback, err, collection);
  2808. }
  2809. // Return stats as third set of values
  2810. handleCallback(callback, err, collection, stats);
  2811. });
  2812. }
  2813. define.classMethod('mapReduce', {callback: true, promise:true});
  2814. /**
  2815. * Initiate a Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order.
  2816. *
  2817. * @method
  2818. * @param {object} [options=null] Optional settings.
  2819. * @param {(number|string)} [options.w=null] The write concern.
  2820. * @param {number} [options.wtimeout=null] The write concern timeout.
  2821. * @param {boolean} [options.j=false] Specify a journal write concern.
  2822. * @return {UnorderedBulkOperation}
  2823. */
  2824. Collection.prototype.initializeUnorderedBulkOp = function(options) {
  2825. options = options || {};
  2826. options.promiseLibrary = this.s.promiseLibrary;
  2827. return unordered(this.s.topology, this, options);
  2828. }
  2829. define.classMethod('initializeUnorderedBulkOp', {callback: false, promise:false, returns: [ordered.UnorderedBulkOperation]});
  2830. /**
  2831. * Initiate an In order bulk write operation, operations will be serially executed in the order they are added, creating a new operation for each switch in types.
  2832. *
  2833. * @method
  2834. * @param {object} [options=null] Optional settings.
  2835. * @param {(number|string)} [options.w=null] The write concern.
  2836. * @param {number} [options.wtimeout=null] The write concern timeout.
  2837. * @param {boolean} [options.j=false] Specify a journal write concern.
  2838. * @param {OrderedBulkOperation} callback The command result callback
  2839. * @return {null}
  2840. */
  2841. Collection.prototype.initializeOrderedBulkOp = function(options) {
  2842. options = options || {};
  2843. options.promiseLibrary = this.s.promiseLibrary;
  2844. return ordered(this.s.topology, this, options);
  2845. }
  2846. define.classMethod('initializeOrderedBulkOp', {callback: false, promise:false, returns: [ordered.OrderedBulkOperation]});
  2847. // Get write concern
  2848. var writeConcern = function(target, db, col, options) {
  2849. if(options.w != null || options.j != null || options.fsync != null) {
  2850. var opts = {};
  2851. if(options.w != null) opts.w = options.w;
  2852. if(options.wtimeout != null) opts.wtimeout = options.wtimeout;
  2853. if(options.j != null) opts.j = options.j;
  2854. if(options.fsync != null) opts.fsync = options.fsync;
  2855. target.writeConcern = opts;
  2856. } else if(col.writeConcern.w != null || col.writeConcern.j != null || col.writeConcern.fsync != null) {
  2857. target.writeConcern = col.writeConcern;
  2858. } else if(db.writeConcern.w != null || db.writeConcern.j != null || db.writeConcern.fsync != null) {
  2859. target.writeConcern = db.writeConcern;
  2860. }
  2861. return target
  2862. }
  2863. // Figure out the read preference
  2864. var getReadPreference = function(self, options, db) {
  2865. var r = null
  2866. if(options.readPreference) {
  2867. r = options.readPreference
  2868. } else if(self.s.readPreference) {
  2869. r = self.s.readPreference
  2870. } else if(db.s.readPreference) {
  2871. r = db.s.readPreference;
  2872. }
  2873. if(r instanceof ReadPreference) {
  2874. options.readPreference = new CoreReadPreference(r.mode, r.tags, {maxStalenessSeconds: r.maxStalenessSeconds});
  2875. } else if(typeof r == 'string') {
  2876. options.readPreference = new CoreReadPreference(r);
  2877. } else if(r && !(r instanceof ReadPreference) && typeof r == 'object') {
  2878. var mode = r.mode || r.preference;
  2879. if (mode && typeof mode == 'string') {
  2880. options.readPreference = new CoreReadPreference(mode, r.tags, {maxStalenessSeconds: r.maxStalenessSeconds});
  2881. }
  2882. }
  2883. return options;
  2884. }
  2885. var testForFields = {
  2886. limit: 1, sort: 1, fields:1, skip: 1, hint: 1, explain: 1, snapshot: 1, timeout: 1, tailable: 1, tailableRetryInterval: 1
  2887. , numberOfRetries: 1, awaitdata: 1, awaitData: 1, exhaust: 1, batchSize: 1, returnKey: 1, maxScan: 1, min: 1, max: 1, showDiskLoc: 1
  2888. , comment: 1, raw: 1, readPreference: 1, partial: 1, read: 1, dbName: 1, oplogReplay: 1, connection: 1, maxTimeMS: 1, transforms: 1
  2889. , collation: 1
  2890. }
  2891. module.exports = Collection;