db.js 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409
  1. "use strict";
  2. var EventEmitter = require('events').EventEmitter
  3. , inherits = require('util').inherits
  4. , getSingleProperty = require('./utils').getSingleProperty
  5. , shallowClone = require('./utils').shallowClone
  6. , parseIndexOptions = require('./utils').parseIndexOptions
  7. , debugOptions = require('./utils').debugOptions
  8. , CommandCursor = require('./command_cursor')
  9. , handleCallback = require('./utils').handleCallback
  10. , toError = require('./utils').toError
  11. , ReadPreference = require('./read_preference')
  12. , f = require('util').format
  13. , Admin = require('./admin')
  14. , Code = require('mongodb-core').BSON.Code
  15. , CoreReadPreference = require('mongodb-core').ReadPreference
  16. , MongoError = require('mongodb-core').MongoError
  17. , ObjectID = require('mongodb-core').ObjectID
  18. , Logger = require('mongodb-core').Logger
  19. , Collection = require('./collection')
  20. , crypto = require('crypto');
  21. var debugFields = ['authSource', 'w', 'wtimeout', 'j', 'native_parser', 'forceServerObjectId'
  22. , 'serializeFunctions', 'raw', 'promoteLongs', 'bufferMaxEntries', 'numberOfRetries', 'retryMiliSeconds'
  23. , 'readPreference', 'pkFactory'];
  24. /**
  25. * @fileOverview The **Db** class is a class that represents a MongoDB Database.
  26. *
  27. * @example
  28. * var MongoClient = require('mongodb').MongoClient,
  29. * test = require('assert');
  30. * // Connection url
  31. * var url = 'mongodb://localhost:27017/test';
  32. * // Connect using MongoClient
  33. * MongoClient.connect(url, function(err, db) {
  34. * // Get an additional db
  35. * var testDb = db.db('test');
  36. * db.close();
  37. * });
  38. */
  39. /**
  40. * Creates a new Db instance
  41. * @class
  42. * @param {string} databaseName The name of the database this instance represents.
  43. * @param {(Server|ReplSet|Mongos)} topology The server topology for the database.
  44. * @param {object} [options=null] Optional settings.
  45. * @param {string} [options.authSource=null] If the database authentication is dependent on another databaseName.
  46. * @param {(number|string)} [options.w=null] The write concern.
  47. * @param {number} [options.wtimeout=null] The write concern timeout.
  48. * @param {boolean} [options.j=false] Specify a journal write concern.
  49. * @param {boolean} [options.native_parser=true] Select C++ bson parser instead of JavaScript parser.
  50. * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver.
  51. * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
  52. * @param {boolean} [options.raw=false] Return document results as raw BSON buffers.
  53. * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution.
  54. * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited.
  55. * @param {number} [options.numberOfRetries=5] Number of retries off connection.
  56. * @param {number} [options.retryMiliSeconds=500] Number of milliseconds between retries.
  57. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  58. * @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys.
  59. * @property {(Server|ReplSet|Mongos)} serverConfig Get the current db topology.
  60. * @property {number} bufferMaxEntries Current bufferMaxEntries value for the database
  61. * @property {string} databaseName The name of the database this instance represents.
  62. * @property {object} options The options associated with the db instance.
  63. * @property {boolean} native_parser The current value of the parameter native_parser.
  64. * @property {boolean} slaveOk The current slaveOk value for the db instance.
  65. * @property {object} writeConcern The current write concern values.
  66. * @fires Db#close
  67. * @fires Db#authenticated
  68. * @fires Db#reconnect
  69. * @fires Db#error
  70. * @fires Db#timeout
  71. * @fires Db#parseError
  72. * @fires Db#fullsetup
  73. * @return {Db} a Db instance.
  74. */
  75. var Db = function(databaseName, topology, options) {
  76. options = options || {};
  77. if(!(this instanceof Db)) return new Db(databaseName, topology, options);
  78. EventEmitter.call(this);
  79. var self = this;
  80. // var self = this; // Internal state of the db object
  81. this.s = {
  82. // Database name
  83. databaseName: databaseName
  84. // Children db's
  85. , children: []
  86. // Topology
  87. , topology: topology
  88. // Options
  89. , options: options
  90. // Logger instance
  91. , logger: Logger('Db', options)
  92. // Get the bson parser
  93. , bson: topology ? topology.bson : null
  94. // Authsource if any
  95. , authSource: options.authSource
  96. // Unpack read preference
  97. , readPreference: options.readPreference
  98. // Set buffermaxEntries
  99. , bufferMaxEntries: typeof options.bufferMaxEntries == 'number' ? options.bufferMaxEntries : -1
  100. // Parent db (if chained)
  101. , parentDb: options.parentDb || null
  102. // Set up the primary key factory or fallback to ObjectID
  103. , pkFactory: options.pkFactory || ObjectID
  104. // Get native parser
  105. , nativeParser: options.nativeParser || options.native_parser
  106. }
  107. // Ensure we have a valid db name
  108. validateDatabaseName(self.s.databaseName);
  109. // If we have specified the type of parser
  110. if(typeof self.s.nativeParser == 'boolean') {
  111. if(self.s.nativeParser) {
  112. topology.setBSONParserType("c++");
  113. } else {
  114. topology.setBSONParserType("js");
  115. }
  116. }
  117. // Add a read Only property
  118. getSingleProperty(this, 'serverConfig', self.s.topology);
  119. getSingleProperty(this, 'bufferMaxEntries', self.s.bufferMaxEntries);
  120. getSingleProperty(this, 'databaseName', self.s.databaseName);
  121. // Last ismaster
  122. Object.defineProperty(this, 'options', {
  123. enumerable:true,
  124. get: function() { return self.s.options; }
  125. });
  126. // Last ismaster
  127. Object.defineProperty(this, 'native_parser', {
  128. enumerable:true,
  129. get: function() { return self.s.topology.parserType() == 'c++'; }
  130. });
  131. // Last ismaster
  132. Object.defineProperty(this, 'slaveOk', {
  133. enumerable:true,
  134. get: function() {
  135. if(self.s.options.readPreference != null
  136. && (self.s.options.readPreference != 'primary' || self.s.options.readPreference.mode != 'primary')) {
  137. return true;
  138. }
  139. return false;
  140. }
  141. });
  142. Object.defineProperty(this, 'writeConcern', {
  143. enumerable:true,
  144. get: function() {
  145. var ops = {};
  146. if(self.s.options.w != null) ops.w = self.s.options.w;
  147. if(self.s.options.j != null) ops.j = self.s.options.j;
  148. if(self.s.options.fsync != null) ops.fsync = self.s.options.fsync;
  149. if(self.s.options.wtimeout != null) ops.wtimeout = self.s.options.wtimeout;
  150. return ops;
  151. }
  152. });
  153. // This is a child db, do not register any listeners
  154. if(options.parentDb) return;
  155. // Add listeners
  156. topology.once('error', createListener(self, 'error', self));
  157. topology.once('timeout', createListener(self, 'timeout', self));
  158. topology.on('close', createListener(self, 'close', self));
  159. topology.once('parseError', createListener(self, 'parseError', self));
  160. topology.once('open', createListener(self, 'open', self));
  161. topology.once('fullsetup', createListener(self, 'fullsetup', self));
  162. topology.once('all', createListener(self, 'all', self));
  163. topology.on('reconnect', createListener(self, 'reconnect', self));
  164. }
  165. inherits(Db, EventEmitter);
  166. /**
  167. * The callback format for the Db.open method
  168. * @callback Db~openCallback
  169. * @param {MongoError} error An error instance representing the error during the execution.
  170. * @param {Db} db The Db instance if the open method was successful.
  171. */
  172. /**
  173. * Open the database
  174. * @method
  175. * @param {Db~openCallback} callback Callback
  176. * @return {null}
  177. */
  178. Db.prototype.open = function(callback) {
  179. var self = this;
  180. self.s.topology.connect(self, self.s.options, function(err, topology) {
  181. if(callback == null) return;
  182. var internalCallback = callback;
  183. callback == null;
  184. if(err) {
  185. self.close();
  186. return internalCallback(err);
  187. }
  188. internalCallback(null, self);
  189. });
  190. }
  191. /**
  192. * The callback format for results
  193. * @callback Db~resultCallback
  194. * @param {MongoError} error An error instance representing the error during the execution.
  195. * @param {object} result The result object if the command was executed successfully.
  196. */
  197. /**
  198. * Execute a command
  199. * @method
  200. * @param {object} command The command hash
  201. * @param {object} [options=null] Optional settings.
  202. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  203. * @param {number} [options.maxTimeMS=null] Number of milliseconds to wait before aborting the query.
  204. * @param {Db~resultCallback} callback The command result callback
  205. * @return {null}
  206. */
  207. Db.prototype.command = function(command, options, callback) {
  208. var self = this;
  209. if(typeof options == 'function') callback = options, options = {};
  210. var dbName = options.dbName || options.authdb || self.s.databaseName;
  211. // Clone the options
  212. options = shallowClone(options);
  213. // If we have a readPreference set
  214. if(options.readPreference == null && self.s.readPreference) {
  215. options.readPreference = self.s.readPreference;
  216. }
  217. // Convert the readPreference
  218. if(options.readPreference && typeof options.readPreference == 'string') {
  219. options.readPreference = new CoreReadPreference(options.readPreference);
  220. } else if(options.readPreference instanceof ReadPreference) {
  221. options.readPreference = new CoreReadPreference(options.readPreference.mode
  222. , options.readPreference.tags);
  223. }
  224. // Debug information
  225. if(self.s.logger.isDebug()) self.s.logger.debug(f('executing command %s against %s with options [%s]'
  226. , JSON.stringify(command), f('%s.$cmd', dbName), JSON.stringify(debugOptions(debugFields, options))));
  227. // Execute command
  228. self.s.topology.command(f('%s.$cmd', dbName), command, options, function(err, result) {
  229. if(err) return handleCallback(callback, err);
  230. handleCallback(callback, null, result.result);
  231. });
  232. }
  233. /**
  234. * The callback format for results
  235. * @callback Db~noResultCallback
  236. * @param {MongoError} error An error instance representing the error during the execution.
  237. * @param {null} result Is not set to a value
  238. */
  239. /**
  240. * Close the db and it's underlying connections
  241. * @method
  242. * @param {boolean} force Force close, emitting no events
  243. * @param {Db~noResultCallback} callback The result callback
  244. * @return {null}
  245. */
  246. Db.prototype.close = function(force, callback) {
  247. if(typeof force == 'function') callback = force, force = false;
  248. this.s.topology.close(force);
  249. var self = this;
  250. // Fire close event if any listeners
  251. if(this.listeners('close').length > 0) {
  252. this.emit('close');
  253. // If it's the top level db emit close on all children
  254. if(this.parentDb == null) {
  255. // Fire close on all children
  256. for(var i = 0; i < this.s.children.length; i++) {
  257. this.s.children[i].emit('close');
  258. }
  259. }
  260. // Remove listeners after emit
  261. self.removeAllListeners('close');
  262. }
  263. // Close parent db if set
  264. if(this.s.parentDb) this.s.parentDb.close();
  265. // Callback after next event loop tick
  266. if(typeof callback == 'function') process.nextTick(function() {
  267. handleCallback(callback, null);
  268. });
  269. }
  270. /**
  271. * Return the Admin db instance
  272. * @method
  273. * @return {Admin} return the new Admin db instance
  274. */
  275. Db.prototype.admin = function() {
  276. return new Admin(this, this.s.topology);
  277. };
  278. /**
  279. * The callback format for the collection method, must be used if strict is specified
  280. * @callback Db~collectionResultCallback
  281. * @param {MongoError} error An error instance representing the error during the execution.
  282. * @param {Collection} collection The collection instance.
  283. */
  284. /**
  285. * Fetch a specific collection (containing the actual collection information). If the application does not use strict mode you can
  286. * can use it without a callback in the following way. var collection = db.collection('mycollection');
  287. *
  288. * @method
  289. * @param {string} name the collection name we wish to access.
  290. * @param {object} [options=null] Optional settings.
  291. * @param {(number|string)} [options.w=null] The write concern.
  292. * @param {number} [options.wtimeout=null] The write concern timeout.
  293. * @param {boolean} [options.j=false] Specify a journal write concern.
  294. * @param {boolean} [options.raw=false] Return document results as raw BSON buffers.
  295. * @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys.
  296. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  297. * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
  298. * @param {boolean} [options.strict=false] Returns an error if the collection does not exist
  299. * @param {Db~collectionResultCallback} callback The collection result callback
  300. * @return {Collection} return the new Collection instance if not in strict mode
  301. */
  302. Db.prototype.collection = function(name, options, callback) {
  303. var self = this;
  304. if(typeof options == 'function') callback = options, options = {};
  305. options = options || {};
  306. if(options == null || !options.strict) {
  307. try {
  308. var collection = new Collection(this, this.s.topology, this.s.databaseName, name, this.s.pkFactory, options);
  309. if(callback) callback(null, collection);
  310. return collection;
  311. } catch(err) {
  312. if(callback) return callback(err);
  313. throw err;
  314. }
  315. }
  316. // Strict mode
  317. if(typeof callback != 'function') {
  318. throw toError(f("A callback is required in strict mode. While getting collection %s.", name));
  319. }
  320. // Strict mode
  321. this.listCollections({name:name}).toArray(function(err, collections) {
  322. if(err != null) return handleCallback(callback, err, null);
  323. if(collections.length == 0) return handleCallback(callback, toError(f("Collection %s does not exist. Currently in strict mode.", name)), null);
  324. try {
  325. return handleCallback(callback, null, new Collection(self, self.s.topology, self.s.databaseName, name, self.s.pkFactory, options));
  326. } catch(err) {
  327. return handleCallback(callback, err, null);
  328. }
  329. });
  330. }
  331. /**
  332. * Creates a collection on a server pre-allocating space, need to create f.ex capped collections.
  333. *
  334. * @method
  335. * @param {string} name the collection name we wish to access.
  336. * @param {object} [options=null] Optional settings.
  337. * @param {(number|string)} [options.w=null] The write concern.
  338. * @param {number} [options.wtimeout=null] The write concern timeout.
  339. * @param {boolean} [options.j=false] Specify a journal write concern.
  340. * @param {boolean} [options.raw=false] Return document results as raw BSON buffers.
  341. * @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys.
  342. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  343. * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
  344. * @param {boolean} [options.strict=false] Returns an error if the collection does not exist
  345. * @param {boolean} [options.capped=false] Create a capped collection.
  346. * @param {number} [options.size=null] The size of the capped collection in bytes.
  347. * @param {number} [options.max=null] The maximum number of documents in the capped collection.
  348. * @param {boolean} [options.autoIndexId=true] Create an index on the _id field of the document, True by default on MongoDB 2.2 or higher off for version < 2.2.
  349. * @param {Db~collectionResultCallback} callback The results callback
  350. * @return {null}
  351. */
  352. Db.prototype.createCollection = function(name, options, callback) {
  353. var self = this;
  354. var args = Array.prototype.slice.call(arguments, 0);
  355. callback = args.pop();
  356. name = args.length ? args.shift() : null;
  357. options = args.length ? args.shift() || {} : {};
  358. // Get the write concern options
  359. var finalOptions = writeConcern(shallowClone(options), this, options);
  360. // Check if we have the name
  361. this.listCollections({name: name}).toArray(function(err, collections) {
  362. if(err != null) return handleCallback(callback, err, null);
  363. if(collections.length > 0 && finalOptions.strict) {
  364. return handleCallback(callback, new MongoError(f("Collection %s already exists. Currently in strict mode.", name)), null);
  365. } else if (collections.length > 0) {
  366. try { return handleCallback(callback, null, new Collection(self, self.s.topology, self.s.databaseName, name, self.s.pkFactory, options)); }
  367. catch(err) { return handleCallback(callback, err); }
  368. }
  369. // Create collection command
  370. var cmd = {'create':name};
  371. // Add all optional parameters
  372. for(var n in options) {
  373. if(options[n] != null && typeof options[n] != 'function')
  374. cmd[n] = options[n];
  375. }
  376. // Execute command
  377. self.command(cmd, finalOptions, function(err, result) {
  378. if(err) return handleCallback(callback, err);
  379. handleCallback(callback, null, new Collection(self, self.s.topology, self.s.databaseName, name, self.s.pkFactory, options));
  380. });
  381. });
  382. }
  383. /**
  384. * Get all the db statistics.
  385. *
  386. * @method
  387. * @param {object} [options=null] Optional settings.
  388. * @param {number} [options.scale=null] Divide the returned sizes by scale value.
  389. * @param {Db~resultCallback} callback The collection result callback
  390. * @return {null}
  391. */
  392. Db.prototype.stats = function(options, callback) {
  393. if(typeof options == 'function') callback = options, options = {};
  394. options = options || {};
  395. // Build command object
  396. var commandObject = { dbStats:true };
  397. // Check if we have the scale value
  398. if(options['scale'] != null) commandObject['scale'] = options['scale'];
  399. // Execute the command
  400. this.command(commandObject, options, callback);
  401. }
  402. // Transformation methods for cursor results
  403. var listCollectionsTranforms = function(databaseName) {
  404. var matching = f('%s.', databaseName);
  405. return {
  406. doc: function(doc) {
  407. var index = doc.name.indexOf(matching);
  408. // Remove database name if available
  409. if(doc.name && index == 0) {
  410. doc.name = doc.name.substr(index + matching.length);
  411. }
  412. return doc;
  413. }
  414. }
  415. }
  416. /**
  417. * Get the list of all collection information for the specified db.
  418. *
  419. * @method
  420. * @param {object} filter Query to filter collections by
  421. * @param {object} [options=null] Optional settings.
  422. * @param {number} [options.batchSize=null] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection
  423. * @return {CommandCursor}
  424. */
  425. Db.prototype.listCollections = function(filter, options) {
  426. filter = filter || {};
  427. options = options || {};
  428. // We have a list collections command
  429. if(this.serverConfig.capabilities().hasListCollectionsCommand) {
  430. // Cursor options
  431. var cursor = options.batchSize ? {batchSize: options.batchSize} : {}
  432. // Build the command
  433. var command = { listCollections : true, filter: filter, cursor: cursor };
  434. // Set the AggregationCursor constructor
  435. options.cursorFactory = CommandCursor;
  436. // Filter out the correct field values
  437. options.transforms = listCollectionsTranforms(this.s.databaseName);
  438. // Execute the cursor
  439. return this.s.topology.cursor(f('%s.$cmd', this.s.databaseName), command, options);
  440. }
  441. // We cannot use the listCollectionsCommand
  442. if(!this.serverConfig.capabilities().hasListCollectionsCommand) {
  443. // If we have legacy mode and have not provided a full db name filter it
  444. if(typeof filter.name == 'string' && !(new RegExp('^' + this.databaseName + '\\.').test(filter.name))) {
  445. filter = shallowClone(filter);
  446. filter.name = f('%s.%s', this.s.databaseName, filter.name);
  447. }
  448. }
  449. // No filter, filter by current database
  450. if(filter == null) {
  451. filter.name = f('/%s/', this.s.databaseName);
  452. }
  453. // Rewrite the filter to use $and to filter out indexes
  454. if(filter.name) {
  455. filter = {$and: [{name: filter.name}, {name:/^((?!\$).)*$/}]};
  456. } else {
  457. filter = {name:/^((?!\$).)*$/};
  458. }
  459. // Return options
  460. var options = {transforms: listCollectionsTranforms(this.s.databaseName)}
  461. // Get the cursor
  462. var cursor = this.collection(Db.SYSTEM_NAMESPACE_COLLECTION).find(filter, options);
  463. // Set the passed in batch size if one was provided
  464. if(options.batchSize) cursor = cursor.batchSize(options.batchSize);
  465. // We have a fallback mode using legacy systems collections
  466. return cursor;
  467. };
  468. /**
  469. * Evaluate JavaScript on the server
  470. *
  471. * @method
  472. * @param {Code} code JavaScript to execute on server.
  473. * @param {(object|array)} parameters The parameters for the call.
  474. * @param {object} [options=null] Optional settings.
  475. * @param {boolean} [options.nolock=false] Tell MongoDB not to block on the evaulation of the javascript.
  476. * @param {Db~resultCallback} callback The results callback
  477. * @return {null}
  478. */
  479. Db.prototype.eval = function(code, parameters, options, callback) {
  480. var self = this;
  481. var args = Array.prototype.slice.call(arguments, 1);
  482. callback = args.pop();
  483. parameters = args.length ? args.shift() : parameters;
  484. options = args.length ? args.shift() || {} : {};
  485. var finalCode = code;
  486. var finalParameters = [];
  487. // If not a code object translate to one
  488. if(!(finalCode instanceof Code)) finalCode = new Code(finalCode);
  489. // Ensure the parameters are correct
  490. if(parameters != null && !Array.isArray(parameters) && typeof parameters !== 'function') {
  491. finalParameters = [parameters];
  492. } else if(parameters != null && Array.isArray(parameters) && typeof parameters !== 'function') {
  493. finalParameters = parameters;
  494. }
  495. // Create execution selector
  496. var cmd = {'$eval':finalCode, 'args':finalParameters};
  497. // Check if the nolock parameter is passed in
  498. if(options['nolock']) {
  499. cmd['nolock'] = options['nolock'];
  500. }
  501. // Set primary read preference
  502. options.readPreference = new CoreReadPreference(ReadPreference.PRIMARY);
  503. // Execute the command
  504. self.command(cmd, options, function(err, result) {
  505. if(err) return handleCallback(callback, err, null);
  506. if(result && result.ok == 1) return handleCallback(callback, null, result.retval);
  507. if(result) return handleCallback(callback, new MongoError(f("eval failed: %s", result.errmsg)), null);
  508. handleCallback(callback, err, result);
  509. });
  510. };
  511. /**
  512. * Rename a collection.
  513. *
  514. * @method
  515. * @param {string} fromCollection Name of current collection to rename.
  516. * @param {string} toCollection New name of of the collection.
  517. * @param {object} [options=null] Optional settings.
  518. * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists.
  519. * @param {Db~collectionResultCallback} callback The results callback
  520. * @return {null}
  521. */
  522. Db.prototype.renameCollection = function(fromCollection, toCollection, options, callback) {
  523. if(typeof options == 'function') callback = options, options = {};
  524. // Add return new collection
  525. options.new_collection = true;
  526. // Execute using the collection method
  527. this.collection(fromCollection).rename(toCollection, options, callback);
  528. };
  529. /**
  530. * Drop a collection from the database, removing it permanently. New accesses will create a new collection.
  531. *
  532. * @method
  533. * @param {string} name Name of collection to drop
  534. * @param {Db~resultCallback} callback The results callback
  535. * @return {null}
  536. */
  537. Db.prototype.dropCollection = function(name, callback) {
  538. callback || (callback = function(){});
  539. // Command to execute
  540. var cmd = {'drop':name}
  541. // Execute command
  542. this.command(cmd, this.s.options, function(err, result) {
  543. if(err) return handleCallback(callback, err);
  544. if(result.ok) return handleCallback(callback, null, true);
  545. handleCallback(callback, null, false);
  546. });
  547. };
  548. /**
  549. * Drop a database.
  550. *
  551. * @method
  552. * @param {Db~resultCallback} [callback] The results callback
  553. * @return {null}
  554. */
  555. Db.prototype.dropDatabase = function(callback) {
  556. if(typeof options == 'function') callback = options, options = {};
  557. // Drop database command
  558. var cmd = {'dropDatabase':1};
  559. // Execute the command
  560. this.command(cmd, this.s.options, function(err, result) {
  561. if(callback == null) return;
  562. if(err) return handleCallback(callback, err, null);
  563. handleCallback(callback, null, result.ok ? true : false);
  564. });
  565. }
  566. /**
  567. * The callback format for the collections method.
  568. * @callback Db~collectionsResultCallback
  569. * @param {MongoError} error An error instance representing the error during the execution.
  570. * @param {Collection[]} collections An array of all the collections objects for the db instance.
  571. */
  572. /**
  573. * Fetch all collections for the current db.
  574. *
  575. * @method
  576. * @param {Db~collectionsResultCallback} [callback] The results callback
  577. * @return {null}
  578. */
  579. Db.prototype.collections = function(callback) {
  580. var self = this;
  581. // Let's get the collection names
  582. this.listCollections().toArray(function(err, documents) {
  583. if(err != null) return handleCallback(callback, err, null);
  584. // Filter collections removing any illegal ones
  585. documents = documents.filter(function(doc) {
  586. return doc.name.indexOf('$') == -1;
  587. });
  588. // Return the collection objects
  589. handleCallback(callback, null, documents.map(function(d) {
  590. return new Collection(self, self.s.topology, self.s.databaseName, d.name.replace(self.s.databaseName + ".", ''), self.s.pkFactory, self.s.options);
  591. }));
  592. });
  593. };
  594. /**
  595. * Runs a command on the database as admin.
  596. * @method
  597. * @param {object} command The command hash
  598. * @param {object} [options=null] Optional settings.
  599. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  600. * @param {number} [options.maxTimeMS=null] Number of milliseconds to wait before aborting the query.
  601. * @param {Db~resultCallback} callback The command result callback
  602. * @return {null}
  603. */
  604. Db.prototype.executeDbAdminCommand = function(selector, options, callback) {
  605. if(typeof options == 'function') callback = options, options = {};
  606. if(options.readPreference) {
  607. options.readPreference = options.readPreference;
  608. }
  609. // Execute command
  610. this.s.topology.command('admin.$cmd', selector, options, function(err, result) {
  611. if(err) return handleCallback(callback, err);
  612. handleCallback(callback, null, result.result);
  613. });
  614. };
  615. /**
  616. * Creates an index on the db and collection collection.
  617. * @method
  618. * @param {string} name Name of the collection to create the index on.
  619. * @param {(string|object)} fieldOrSpec Defines the index.
  620. * @param {object} [options=null] Optional settings.
  621. * @param {(number|string)} [options.w=null] The write concern.
  622. * @param {number} [options.wtimeout=null] The write concern timeout.
  623. * @param {boolean} [options.j=false] Specify a journal write concern.
  624. * @param {boolean} [options.unique=false] Creates an unique index.
  625. * @param {boolean} [options.sparse=false] Creates a sparse index.
  626. * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible.
  627. * @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
  628. * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates.
  629. * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates.
  630. * @param {number} [options.v=null] Specify the format version of the indexes.
  631. * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)
  632. * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes)
  633. * @param {Db~resultCallback} callback The command result callback
  634. * @return {null}
  635. */
  636. Db.prototype.createIndex = function(name, fieldOrSpec, options, callback) {
  637. var self = this;
  638. var args = Array.prototype.slice.call(arguments, 2);
  639. callback = args.pop();
  640. options = args.length ? args.shift() || {} : {};
  641. options = typeof callback === 'function' ? options : callback;
  642. options = options == null ? {} : options;
  643. // Clone options
  644. options = shallowClone(options);
  645. // Run only against primary
  646. options.readPreference = ReadPreference.PRIMARY;
  647. // Get the write concern options
  648. var finalOptions = writeConcern({}, self, options);
  649. // Ensure we have a callback
  650. if(finalOptions.writeConcern && typeof callback != 'function') {
  651. throw new MongoError("Cannot use a writeConcern without a provided callback");
  652. }
  653. // Shallow clone the options
  654. options = shallowClone(options);
  655. // Always set read preference to primary
  656. options.readPreference = ReadPreference.PRIMARY;
  657. // Attempt to run using createIndexes command
  658. createIndexUsingCreateIndexes(self, name, fieldOrSpec, options, function(err, result) {
  659. if(err == null) return handleCallback(callback, err, result);
  660. // Create command
  661. var doc = createCreateIndexCommand(self, name, fieldOrSpec, options);
  662. // Set no key checking
  663. finalOptions.checkKeys = false;
  664. // Insert document
  665. self.s.topology.insert(f("%s.%s", self.s.databaseName, Db.SYSTEM_INDEX_COLLECTION), doc, finalOptions, function(err, result) {
  666. if(callback == null) return;
  667. if(err) return handleCallback(callback, err);
  668. if(result == null) return handleCallback(callback, null, null);
  669. if(result.result.writeErrors) return handleCallback(callback, MongoError.create(result.result.writeErrors[0]), null);
  670. handleCallback(callback, null, doc.name);
  671. });
  672. });
  673. };
  674. /**
  675. * Ensures that an index exists, if it does not it creates it
  676. * @method
  677. * @deprecated since version 2.0
  678. * @param {string} name The index name
  679. * @param {(string|object)} fieldOrSpec Defines the index.
  680. * @param {object} [options=null] Optional settings.
  681. * @param {(number|string)} [options.w=null] The write concern.
  682. * @param {number} [options.wtimeout=null] The write concern timeout.
  683. * @param {boolean} [options.j=false] Specify a journal write concern.
  684. * @param {boolean} [options.unique=false] Creates an unique index.
  685. * @param {boolean} [options.sparse=false] Creates a sparse index.
  686. * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible.
  687. * @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
  688. * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates.
  689. * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates.
  690. * @param {number} [options.v=null] Specify the format version of the indexes.
  691. * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)
  692. * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes)
  693. * @param {Db~resultCallback} callback The command result callback
  694. * @return {null}
  695. */
  696. Db.prototype.ensureIndex = function(name, fieldOrSpec, options, callback) {
  697. var self = this;
  698. if(typeof options == 'function') callback = options, options = {};
  699. options = options || {};
  700. // Clone options
  701. options = shallowClone(options);
  702. // Run only against primary
  703. options.readPreference = ReadPreference.PRIMARY;
  704. // Get the write concern options
  705. var finalOptions = writeConcern({}, self, options);
  706. // Create command
  707. var selector = createCreateIndexCommand(self, name, fieldOrSpec, options);
  708. var index_name = selector.name;
  709. // Default command options
  710. var commandOptions = {};
  711. // Check if the index allready exists
  712. this.indexInformation(name, finalOptions, function(err, indexInformation) {
  713. if(err != null && err.code != 26) return handleCallback(callback, err, null);
  714. // If the index does not exist, create it
  715. if(indexInformation == null || !indexInformation[index_name]) {
  716. self.createIndex(name, fieldOrSpec, options, callback);
  717. } else {
  718. if(typeof callback === 'function') return handleCallback(callback, null, index_name);
  719. }
  720. });
  721. };
  722. Db.prototype.addChild = function(db) {
  723. if(this.s.parentDb) return this.s.parentDb.addChild(db);
  724. this.s.children.push(db);
  725. }
  726. /**
  727. * Create a new Db instance sharing the current socket connections.
  728. * @method
  729. * @param {string} name The name of the database we want to use.
  730. * @return {Db}
  731. */
  732. Db.prototype.db = function(dbName) {
  733. // Copy the options and add out internal override of the not shared flag
  734. var options = {};
  735. for(var key in this.options) {
  736. options[key] = this.options[key];
  737. }
  738. // Add current db as parentDb
  739. options.parentDb = this;
  740. // Return the db object
  741. var db = new Db(dbName, this.s.topology, options)
  742. // Keep reference to the object
  743. // if(this.s.parentDb) {
  744. // this.s.parentDb.s.children.push(db);
  745. this.addChild(db);
  746. // }
  747. // this.s.children.push(db);
  748. // // Add listeners to the parent database
  749. // this.once('error', createListener(this, 'error', db));
  750. // this.once('timeout', createListener(this, 'timeout', db));
  751. // this.once('close', createListener(this, 'close', db));
  752. // this.once('parseError', createListener(this, 'parseError', db));
  753. // Return the database
  754. return db;
  755. };
  756. var _executeAuthCreateUserCommand = function(self, username, password, options, callback) {
  757. // Special case where there is no password ($external users)
  758. if(typeof username == 'string'
  759. && password != null && typeof password == 'object') {
  760. options = password;
  761. password = null;
  762. }
  763. // Unpack all options
  764. if(typeof options == 'function') {
  765. callback = options;
  766. options = {};
  767. }
  768. // Error out if we digestPassword set
  769. if(options.digestPassword != null) {
  770. throw toError("The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option.");
  771. }
  772. // Get additional values
  773. var customData = options.customData != null ? options.customData : {};
  774. var roles = Array.isArray(options.roles) ? options.roles : [];
  775. var maxTimeMS = typeof options.maxTimeMS == 'number' ? options.maxTimeMS : null;
  776. // If not roles defined print deprecated message
  777. if(roles.length == 0) {
  778. console.log("Creating a user without roles is deprecated in MongoDB >= 2.6");
  779. }
  780. // Get the error options
  781. var commandOptions = {writeCommand:true};
  782. if(options['dbName']) commandOptions.dbName = options['dbName'];
  783. // Add maxTimeMS to options if set
  784. if(maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS;
  785. // Check the db name and add roles if needed
  786. if((self.databaseName.toLowerCase() == 'admin' || options.dbName == 'admin') && !Array.isArray(options.roles)) {
  787. roles = ['root']
  788. } else if(!Array.isArray(options.roles)) {
  789. roles = ['dbOwner']
  790. }
  791. // Build the command to execute
  792. var command = {
  793. createUser: username
  794. , customData: customData
  795. , roles: roles
  796. , digestPassword:false
  797. }
  798. // Apply write concern to command
  799. command = writeConcern(command, self, options);
  800. // Use node md5 generator
  801. var md5 = crypto.createHash('md5');
  802. // Generate keys used for authentication
  803. md5.update(username + ":mongo:" + password);
  804. var userPassword = md5.digest('hex');
  805. // No password
  806. if(typeof password == 'string') {
  807. command.pwd = userPassword;
  808. }
  809. // Force write using primary
  810. commandOptions.readPreference = CoreReadPreference.primary;
  811. // Execute the command
  812. self.command(command, commandOptions, function(err, result) {
  813. if(err && err.ok == 0 && err.code == undefined) return handleCallback(callback, {code: -5000}, null);
  814. if(err) return handleCallback(callback, err, null);
  815. handleCallback(callback, !result.ok ? toError(result) : null
  816. , result.ok ? [{user: username, pwd: ''}] : null);
  817. })
  818. }
  819. /**
  820. * Add a user to the database.
  821. * @method
  822. * @param {string} username The username.
  823. * @param {string} password The password.
  824. * @param {object} [options=null] Optional settings.
  825. * @param {(number|string)} [options.w=null] The write concern.
  826. * @param {number} [options.wtimeout=null] The write concern timeout.
  827. * @param {boolean} [options.j=false] Specify a journal write concern.
  828. * @param {object} [options.customData=null] Custom data associated with the user (only Mongodb 2.6 or higher)
  829. * @param {object[]} [options.roles=null] Roles associated with the created user (only Mongodb 2.6 or higher)
  830. * @param {Db~resultCallback} callback The command result callback
  831. * @return {null}
  832. */
  833. Db.prototype.addUser = function(username, password, options, callback) {
  834. // Unpack the parameters
  835. var self = this;
  836. var args = Array.prototype.slice.call(arguments, 2);
  837. callback = args.pop();
  838. options = args.length ? args.shift() || {} : {};
  839. // Attempt to execute auth command
  840. _executeAuthCreateUserCommand(this, username, password, options, function(err, r) {
  841. // We need to perform the backward compatible insert operation
  842. if(err && err.code == -5000) {
  843. var finalOptions = writeConcern(shallowClone(options), self, options);
  844. // Use node md5 generator
  845. var md5 = crypto.createHash('md5');
  846. // Generate keys used for authentication
  847. md5.update(username + ":mongo:" + password);
  848. var userPassword = md5.digest('hex');
  849. // If we have another db set
  850. var db = options.dbName ? self.db(options.dbName) : self;
  851. // Fetch a user collection
  852. var collection = db.collection(Db.SYSTEM_USER_COLLECTION);
  853. // Check if we are inserting the first user
  854. collection.count({}, function(err, count) {
  855. // We got an error (f.ex not authorized)
  856. if(err != null) return handleCallback(callback, err, null);
  857. // Check if the user exists and update i
  858. collection.find({user: username}, {dbName: options['dbName']}).toArray(function(err, documents) {
  859. // We got an error (f.ex not authorized)
  860. if(err != null) return handleCallback(callback, err, null);
  861. // Add command keys
  862. finalOptions.upsert = true;
  863. // We have a user, let's update the password or upsert if not
  864. collection.update({user: username},{$set: {user: username, pwd: userPassword}}, finalOptions, function(err, results, full) {
  865. if(count == 0 && err) return handleCallback(callback, null, [{user:username, pwd:userPassword}]);
  866. if(err) return handleCallback(callback, err, null)
  867. handleCallback(callback, null, [{user:username, pwd:userPassword}]);
  868. });
  869. });
  870. });
  871. return;
  872. }
  873. if(err) return handleCallback(callback, err);
  874. handleCallback(callback, err, r);
  875. });
  876. };
  877. var _executeAuthRemoveUserCommand = function(self, username, options, callback) {
  878. if(typeof options == 'function') callback = options, options = {};
  879. // Get the error options
  880. var commandOptions = {writeCommand:true};
  881. if(options['dbName']) commandOptions.dbName = options['dbName'];
  882. // Get additional values
  883. var maxTimeMS = typeof options.maxTimeMS == 'number' ? options.maxTimeMS : null;
  884. // Add maxTimeMS to options if set
  885. if(maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS;
  886. // Build the command to execute
  887. var command = {
  888. dropUser: username
  889. }
  890. // Apply write concern to command
  891. command = writeConcern(command, self, options);
  892. // Force write using primary
  893. commandOptions.readPreference = CoreReadPreference.primary;
  894. // Execute the command
  895. self.command(command, commandOptions, function(err, result) {
  896. if(err && !err.ok && err.code == undefined) return handleCallback(callback, {code: -5000});
  897. if(err) return handleCallback(callback, err, null);
  898. handleCallback(callback, null, result.ok ? true : false);
  899. })
  900. }
  901. /**
  902. * Remove a user from a database
  903. * @method
  904. * @param {string} username The username.
  905. * @param {object} [options=null] Optional settings.
  906. * @param {(number|string)} [options.w=null] The write concern.
  907. * @param {number} [options.wtimeout=null] The write concern timeout.
  908. * @param {boolean} [options.j=false] Specify a journal write concern.
  909. * @param {Db~resultCallback} callback The command result callback
  910. * @return {null}
  911. */
  912. Db.prototype.removeUser = function(username, options, callback) {
  913. // Unpack the parameters
  914. var self = this;
  915. var args = Array.prototype.slice.call(arguments, 1);
  916. callback = args.pop();
  917. options = args.length ? args.shift() || {} : {};
  918. // Attempt to execute command
  919. _executeAuthRemoveUserCommand(this, username, options, function(err, result) {
  920. if(err && err.code == -5000) {
  921. var finalOptions = writeConcern(shallowClone(options), self, options);
  922. // If we have another db set
  923. var db = options.dbName ? self.db(options.dbName) : self;
  924. // Fetch a user collection
  925. var collection = db.collection(Db.SYSTEM_USER_COLLECTION);
  926. // Locate the user
  927. collection.findOne({user: username}, {}, function(err, user) {
  928. if(user == null) return handleCallback(callback, err, false);
  929. collection.remove({user: username}, finalOptions, function(err, result) {
  930. handleCallback(callback, err, true);
  931. });
  932. });
  933. return;
  934. }
  935. if(err) return handleCallback(callback, err);
  936. handleCallback(callback, err, result);
  937. });
  938. };
  939. /**
  940. * Authenticate a user against the server.
  941. * @method
  942. * @param {string} username The username.
  943. * @param {string} [password] The password.
  944. * @param {object} [options=null] Optional settings.
  945. * @param {string} [options.authMechanism=MONGODB-CR] The authentication mechanism to use, GSSAPI, MONGODB-CR, MONGODB-X509, SCRAM-SHA-1, PLAIN
  946. * @param {Db~resultCallback} callback The command result callback
  947. * @return {null}
  948. */
  949. Db.prototype.authenticate = function(username, password, options, callback) {
  950. if(typeof options == 'function') callback = options, options = {};
  951. var self = this;
  952. // Shallow copy the options
  953. options = shallowClone(options);
  954. // Set default mechanism
  955. if(!options.authMechanism) {
  956. options.authMechanism = 'DEFAULT';
  957. } else if(options.authMechanism != 'GSSAPI'
  958. && options.authMechanism != 'MONGODB-CR'
  959. && options.authMechanism != 'MONGODB-X509'
  960. && options.authMechanism != 'SCRAM-SHA-1'
  961. && options.authMechanism != 'PLAIN') {
  962. return handleCallback(callback, new MongoError("only GSSAPI, PLAIN, MONGODB-X509, SCRAM-SHA-1 or MONGODB-CR is supported by authMechanism"));
  963. }
  964. // the default db to authenticate against is 'this'
  965. // if authententicate is called from a retry context, it may be another one, like admin
  966. var authdb = options.authdb ? options.authdb : options.dbName;
  967. authdb = options.authSource ? options.authSource : authdb;
  968. authdb = authdb ? authdb : this.databaseName;
  969. // Callback
  970. var _callback = function(err, result) {
  971. if(self.listeners('authenticated').length > 0) {
  972. self.emit('authenticated', err, result);
  973. }
  974. // Return to caller
  975. handleCallback(callback, err, result);
  976. }
  977. // authMechanism
  978. var authMechanism = options.authMechanism || '';
  979. authMechanism = authMechanism.toUpperCase();
  980. // If classic auth delegate to auth command
  981. if(authMechanism == 'MONGODB-CR') {
  982. this.s.topology.auth('mongocr', authdb, username, password, function(err, result) {
  983. if(err) return handleCallback(callback, err, false);
  984. _callback(null, true);
  985. });
  986. } else if(authMechanism == 'PLAIN') {
  987. this.s.topology.auth('plain', authdb, username, password, function(err, result) {
  988. if(err) return handleCallback(callback, err, false);
  989. _callback(null, true);
  990. });
  991. } else if(authMechanism == 'MONGODB-X509') {
  992. this.s.topology.auth('x509', authdb, username, password, function(err, result) {
  993. if(err) return handleCallback(callback, err, false);
  994. _callback(null, true);
  995. });
  996. } else if(authMechanism == 'SCRAM-SHA-1') {
  997. this.s.topology.auth('scram-sha-1', authdb, username, password, function(err, result) {
  998. if(err) return handleCallback(callback, err, false);
  999. _callback(null, true);
  1000. });
  1001. } else if(authMechanism == 'GSSAPI') {
  1002. if(process.platform == 'win32') {
  1003. this.s.topology.auth('sspi', authdb, username, password, options, function(err, result) {
  1004. if(err) return handleCallback(callback, err, false);
  1005. _callback(null, true);
  1006. });
  1007. } else {
  1008. this.s.topology.auth('gssapi', authdb, username, password, options, function(err, result) {
  1009. if(err) return handleCallback(callback, err, false);
  1010. _callback(null, true);
  1011. });
  1012. }
  1013. } else if(authMechanism == 'DEFAULT') {
  1014. this.s.topology.auth('default', authdb, username, password, function(err, result) {
  1015. if(err) return handleCallback(callback, err, false);
  1016. _callback(null, true);
  1017. });
  1018. } else {
  1019. handleCallback(callback, new MongoError(f("authentication mechanism %s not supported", options.authMechanism), false));
  1020. }
  1021. };
  1022. /**
  1023. * Logout user from server, fire off on all connections and remove all auth info
  1024. * @method
  1025. * @param {object} [options=null] Optional settings.
  1026. * @param {string} [options.dbName=null] Logout against different database than current.
  1027. * @param {Db~resultCallback} callback The command result callback
  1028. * @return {null}
  1029. */
  1030. Db.prototype.logout = function(options, callback) {
  1031. var args = Array.prototype.slice.call(arguments, 0);
  1032. callback = args.pop();
  1033. options = args.length ? args.shift() || {} : {};
  1034. // logout command
  1035. var cmd = {'logout':1};
  1036. // Add onAll to login to ensure all connection are logged out
  1037. options.onAll = true;
  1038. // We authenticated against a different db use that
  1039. if(this.s.authSource) options.dbName = this.s.authSource;
  1040. // Execute the command
  1041. this.command(cmd, options, function(err, result) {
  1042. if(err) return handleCallback(callback, err, false);
  1043. handleCallback(callback, null, true)
  1044. });
  1045. }
  1046. // Figure out the read preference
  1047. var getReadPreference = function(options, db) {
  1048. if(options.readPreference) return options;
  1049. if(db.readPreference) options.readPreference = db.readPreference;
  1050. return options;
  1051. }
  1052. /**
  1053. * Retrieves this collections index info.
  1054. * @method
  1055. * @param {string} name The name of the collection.
  1056. * @param {object} [options=null] Optional settings.
  1057. * @param {boolean} [options.full=false] Returns the full raw index information.
  1058. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  1059. * @param {Db~resultCallback} callback The command result callback
  1060. * @return {null}
  1061. */
  1062. Db.prototype.indexInformation = function(name, options, callback) {
  1063. if(typeof callback === 'undefined') {
  1064. if(typeof options === 'undefined') {
  1065. callback = name;
  1066. name = null;
  1067. } else {
  1068. callback = options;
  1069. }
  1070. options = {};
  1071. }
  1072. // If we specified full information
  1073. var full = options['full'] == null ? false : options['full'];
  1074. var self = this;
  1075. // Process all the results from the index command and collection
  1076. var processResults = function(indexes) {
  1077. // Contains all the information
  1078. var info = {};
  1079. // Process all the indexes
  1080. for(var i = 0; i < indexes.length; i++) {
  1081. var index = indexes[i];
  1082. // Let's unpack the object
  1083. info[index.name] = [];
  1084. for(var name in index.key) {
  1085. info[index.name].push([name, index.key[name]]);
  1086. }
  1087. }
  1088. return info;
  1089. }
  1090. // Get the list of indexes of the specified collection
  1091. this.collection(name).listIndexes().toArray(function(err, indexes) {
  1092. if(err) return callback(toError(err));
  1093. if(!Array.isArray(indexes)) return handleCallback(callback, null, []);
  1094. if(full) return handleCallback(callback, null, indexes);
  1095. handleCallback(callback, null, processResults(indexes));
  1096. });
  1097. };
  1098. var createCreateIndexCommand = function(db, name, fieldOrSpec, options) {
  1099. var indexParameters = parseIndexOptions(fieldOrSpec);
  1100. var fieldHash = indexParameters.fieldHash;
  1101. var keys = indexParameters.keys;
  1102. // Generate the index name
  1103. var indexName = typeof options.name == 'string' ? options.name : indexParameters.name;
  1104. var selector = {
  1105. 'ns': db.databaseName + "." + name, 'key': fieldHash, 'name': indexName
  1106. }
  1107. // Ensure we have a correct finalUnique
  1108. var finalUnique = options == null || 'object' === typeof options ? false : options;
  1109. // Set up options
  1110. options = options == null || typeof options == 'boolean' ? {} : options;
  1111. // Add all the options
  1112. var keysToOmit = Object.keys(selector);
  1113. for(var optionName in options) {
  1114. if(keysToOmit.indexOf(optionName) == -1) {
  1115. selector[optionName] = options[optionName];
  1116. }
  1117. }
  1118. if(selector['unique'] == null) selector['unique'] = finalUnique;
  1119. // Remove any write concern operations
  1120. var removeKeys = ['w', 'wtimeout', 'j', 'fsync', 'readPreference'];
  1121. for(var i = 0; i < removeKeys.length; i++) {
  1122. delete selector[removeKeys[i]];
  1123. }
  1124. // Return the command creation selector
  1125. return selector;
  1126. }
  1127. var createIndexUsingCreateIndexes = function(self, name, fieldOrSpec, options, callback) {
  1128. // Build the index
  1129. var indexParameters = parseIndexOptions(fieldOrSpec);
  1130. // Generate the index name
  1131. var indexName = typeof options.name == 'string' ? options.name : indexParameters.name;
  1132. // Set up the index
  1133. var indexes = [{ name: indexName, key: indexParameters.fieldHash }];
  1134. // merge all the options
  1135. var keysToOmit = Object.keys(indexes[0]);
  1136. for(var optionName in options) {
  1137. if(keysToOmit.indexOf(optionName) == -1) {
  1138. indexes[0][optionName] = options[optionName];
  1139. }
  1140. // Remove any write concern operations
  1141. var removeKeys = ['w', 'wtimeout', 'j', 'fsync', 'readPreference'];
  1142. for(var i = 0; i < removeKeys.length; i++) {
  1143. delete indexes[0][removeKeys[i]];
  1144. }
  1145. }
  1146. // Create command
  1147. var cmd = {createIndexes: name, indexes: indexes};
  1148. // Apply write concern to command
  1149. cmd = writeConcern(cmd, self, options);
  1150. // Build the command
  1151. self.command(cmd, options, function(err, result) {
  1152. if(err) return handleCallback(callback, err, null);
  1153. if(result.ok == 0) return handleCallback(callback, toError(result), null);
  1154. // Return the indexName for backward compatibility
  1155. handleCallback(callback, null, indexName);
  1156. });
  1157. }
  1158. // Validate the database name
  1159. var validateDatabaseName = function(databaseName) {
  1160. if(typeof databaseName !== 'string') throw new MongoError("database name must be a string");
  1161. if(databaseName.length === 0) throw new MongoError("database name cannot be the empty string");
  1162. if(databaseName == '$external') return;
  1163. var invalidChars = [" ", ".", "$", "/", "\\"];
  1164. for(var i = 0; i < invalidChars.length; i++) {
  1165. if(databaseName.indexOf(invalidChars[i]) != -1) throw new MongoError("database names cannot contain the character '" + invalidChars[i] + "'");
  1166. }
  1167. }
  1168. // Get write concern
  1169. var writeConcern = function(target, db, options) {
  1170. if(options.w != null || options.j != null || options.fsync != null) {
  1171. var opts = {};
  1172. if(options.w) opts.w = options.w;
  1173. if(options.wtimeout) opts.wtimeout = options.wtimeout;
  1174. if(options.j) opts.j = options.j;
  1175. if(options.fsync) opts.fsync = options.fsync;
  1176. target.writeConcern = opts;
  1177. } else if(db.writeConcern.w != null || db.writeConcern.j != null || db.writeConcern.fsync != null) {
  1178. target.writeConcern = db.writeConcern;
  1179. }
  1180. return target
  1181. }
  1182. // Add listeners to topology
  1183. var createListener = function(self, e, object) {
  1184. var listener = function(err) {
  1185. if(e != 'error') {
  1186. object.emit(e, err, self);
  1187. // Emit on all associated db's if available
  1188. for(var i = 0; i < self.s.children.length; i++) {
  1189. self.s.children[i].emit(e, err, self.s.children[i]);
  1190. }
  1191. }
  1192. }
  1193. return listener;
  1194. }
  1195. /**
  1196. * Db close event
  1197. *
  1198. * @event Db#close
  1199. * @type {object}
  1200. */
  1201. /**
  1202. * Db authenticated event
  1203. *
  1204. * @event Db#authenticated
  1205. * @type {object}
  1206. */
  1207. /**
  1208. * Db reconnect event
  1209. *
  1210. * @event Db#reconnect
  1211. * @type {object}
  1212. */
  1213. /**
  1214. * Db error event
  1215. *
  1216. * @event Db#error
  1217. * @type {MongoError}
  1218. */
  1219. /**
  1220. * Db timeout event
  1221. *
  1222. * @event Db#timeout
  1223. * @type {object}
  1224. */
  1225. /**
  1226. * Db parseError event
  1227. *
  1228. * @event Db#parseError
  1229. * @type {object}
  1230. */
  1231. /**
  1232. * Db fullsetup event, emitted when all servers in the topology have been connected to.
  1233. *
  1234. * @event Db#fullsetup
  1235. * @type {Db}
  1236. */
  1237. // Constants
  1238. Db.SYSTEM_NAMESPACE_COLLECTION = "system.namespaces";
  1239. Db.SYSTEM_INDEX_COLLECTION = "system.indexes";
  1240. Db.SYSTEM_PROFILE_COLLECTION = "system.profile";
  1241. Db.SYSTEM_USER_COLLECTION = "system.users";
  1242. Db.SYSTEM_COMMAND_COLLECTION = "$cmd";
  1243. Db.SYSTEM_JS_COLLECTION = "system.js";
  1244. module.exports = Db;