collection.js 118 KB

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