db.js 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054
  1. 'use strict';
  2. const EventEmitter = require('events').EventEmitter;
  3. const inherits = require('util').inherits;
  4. const getSingleProperty = require('./utils').getSingleProperty;
  5. const CommandCursor = require('./command_cursor');
  6. const handleCallback = require('./utils').handleCallback;
  7. const filterOptions = require('./utils').filterOptions;
  8. const toError = require('./utils').toError;
  9. const ReadPreference = require('./core').ReadPreference;
  10. const MongoError = require('./core').MongoError;
  11. const ObjectID = require('./core').ObjectID;
  12. const Logger = require('./core').Logger;
  13. const Collection = require('./collection');
  14. const conditionallyMergeWriteConcern = require('./utils').conditionallyMergeWriteConcern;
  15. const executeLegacyOperation = require('./utils').executeLegacyOperation;
  16. const ChangeStream = require('./change_stream');
  17. const deprecate = require('util').deprecate;
  18. const deprecateOptions = require('./utils').deprecateOptions;
  19. const MongoDBNamespace = require('./utils').MongoDBNamespace;
  20. const CONSTANTS = require('./constants');
  21. const WriteConcern = require('./write_concern');
  22. const ReadConcern = require('./read_concern');
  23. const AggregationCursor = require('./aggregation_cursor');
  24. // Operations
  25. const createListener = require('./operations/db_ops').createListener;
  26. const ensureIndex = require('./operations/db_ops').ensureIndex;
  27. const evaluate = require('./operations/db_ops').evaluate;
  28. const profilingInfo = require('./operations/db_ops').profilingInfo;
  29. const validateDatabaseName = require('./operations/db_ops').validateDatabaseName;
  30. const AggregateOperation = require('./operations/aggregate');
  31. const AddUserOperation = require('./operations/add_user');
  32. const CollectionsOperation = require('./operations/collections');
  33. const CommandOperation = require('./operations/command');
  34. const RunCommandOperation = require('./operations/run_command');
  35. const CreateCollectionOperation = require('./operations/create_collection');
  36. const CreateIndexesOperation = require('./operations/create_indexes');
  37. const DropCollectionOperation = require('./operations/drop').DropCollectionOperation;
  38. const DropDatabaseOperation = require('./operations/drop').DropDatabaseOperation;
  39. const ExecuteDbAdminCommandOperation = require('./operations/execute_db_admin_command');
  40. const IndexInformationOperation = require('./operations/index_information');
  41. const ListCollectionsOperation = require('./operations/list_collections');
  42. const ProfilingLevelOperation = require('./operations/profiling_level');
  43. const RemoveUserOperation = require('./operations/remove_user');
  44. const RenameOperation = require('./operations/rename');
  45. const SetProfilingLevelOperation = require('./operations/set_profiling_level');
  46. const executeOperation = require('./operations/execute_operation');
  47. /**
  48. * @fileOverview The **Db** class is a class that represents a MongoDB Database.
  49. *
  50. * @example
  51. * const MongoClient = require('mongodb').MongoClient;
  52. * // Connection url
  53. * const url = 'mongodb://localhost:27017';
  54. * // Database Name
  55. * const dbName = 'test';
  56. * // Connect using MongoClient
  57. * MongoClient.connect(url, function(err, client) {
  58. * // Select the database by name
  59. * const testDb = client.db(dbName);
  60. * client.close();
  61. * });
  62. */
  63. // Allowed parameters
  64. const legalOptionNames = [
  65. 'w',
  66. 'wtimeout',
  67. 'fsync',
  68. 'j',
  69. 'writeConcern',
  70. 'readPreference',
  71. 'readPreferenceTags',
  72. 'native_parser',
  73. 'forceServerObjectId',
  74. 'pkFactory',
  75. 'serializeFunctions',
  76. 'raw',
  77. 'bufferMaxEntries',
  78. 'authSource',
  79. 'ignoreUndefined',
  80. 'promoteLongs',
  81. 'promiseLibrary',
  82. 'readConcern',
  83. 'retryMiliSeconds',
  84. 'numberOfRetries',
  85. 'parentDb',
  86. 'noListener',
  87. 'loggerLevel',
  88. 'logger',
  89. 'promoteBuffers',
  90. 'promoteLongs',
  91. 'promoteValues',
  92. 'compression',
  93. 'retryWrites'
  94. ];
  95. /**
  96. * Creates a new Db instance
  97. * @class
  98. * @param {string} databaseName The name of the database this instance represents.
  99. * @param {(Server|ReplSet|Mongos)} topology The server topology for the database.
  100. * @param {object} [options] Optional settings.
  101. * @param {string} [options.authSource] If the database authentication is dependent on another databaseName.
  102. * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead.
  103. * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead.
  104. * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead.
  105. * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings.
  106. * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver.
  107. * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
  108. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
  109. * @param {boolean} [options.raw=false] Return document results as raw BSON buffers.
  110. * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution.
  111. * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers.
  112. * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types.
  113. * @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.
  114. * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  115. * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys.
  116. * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible
  117. * @param {object} [options.readConcern] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported)
  118. * @param {ReadConcernLevel} [options.readConcern.level='local'] Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported)
  119. * @property {(Server|ReplSet|Mongos)} serverConfig Get the current db topology.
  120. * @property {number} bufferMaxEntries Current bufferMaxEntries value for the database
  121. * @property {string} databaseName The name of the database this instance represents.
  122. * @property {object} options The options associated with the db instance.
  123. * @property {boolean} native_parser The current value of the parameter native_parser.
  124. * @property {boolean} slaveOk The current slaveOk value for the db instance.
  125. * @property {object} writeConcern The current write concern values.
  126. * @property {object} topology Access the topology object (single server, replicaset or mongos).
  127. * @fires Db#close
  128. * @fires Db#reconnect
  129. * @fires Db#error
  130. * @fires Db#timeout
  131. * @fires Db#parseError
  132. * @fires Db#fullsetup
  133. * @return {Db} a Db instance.
  134. */
  135. function Db(databaseName, topology, options) {
  136. options = options || {};
  137. if (!(this instanceof Db)) return new Db(databaseName, topology, options);
  138. EventEmitter.call(this);
  139. // Get the promiseLibrary
  140. const promiseLibrary = options.promiseLibrary || Promise;
  141. // Filter the options
  142. options = filterOptions(options, legalOptionNames);
  143. // Ensure we put the promiseLib in the options
  144. options.promiseLibrary = promiseLibrary;
  145. // Internal state of the db object
  146. this.s = {
  147. // DbCache
  148. dbCache: {},
  149. // Children db's
  150. children: [],
  151. // Topology
  152. topology: topology,
  153. // Options
  154. options: options,
  155. // Logger instance
  156. logger: Logger('Db', options),
  157. // Get the bson parser
  158. bson: topology ? topology.bson : null,
  159. // Unpack read preference
  160. readPreference: ReadPreference.fromOptions(options),
  161. // Set buffermaxEntries
  162. bufferMaxEntries: typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : -1,
  163. // Parent db (if chained)
  164. parentDb: options.parentDb || null,
  165. // Set up the primary key factory or fallback to ObjectID
  166. pkFactory: options.pkFactory || ObjectID,
  167. // Get native parser
  168. nativeParser: options.nativeParser || options.native_parser,
  169. // Promise library
  170. promiseLibrary: promiseLibrary,
  171. // No listener
  172. noListener: typeof options.noListener === 'boolean' ? options.noListener : false,
  173. // ReadConcern
  174. readConcern: ReadConcern.fromOptions(options),
  175. writeConcern: WriteConcern.fromOptions(options),
  176. // Namespace
  177. namespace: new MongoDBNamespace(databaseName)
  178. };
  179. // Ensure we have a valid db name
  180. validateDatabaseName(databaseName);
  181. // Add a read Only property
  182. getSingleProperty(this, 'serverConfig', this.s.topology);
  183. getSingleProperty(this, 'bufferMaxEntries', this.s.bufferMaxEntries);
  184. getSingleProperty(this, 'databaseName', this.s.namespace.db);
  185. // This is a child db, do not register any listeners
  186. if (options.parentDb) return;
  187. if (this.s.noListener) return;
  188. // Add listeners
  189. topology.on('error', createListener(this, 'error', this));
  190. topology.on('timeout', createListener(this, 'timeout', this));
  191. topology.on('close', createListener(this, 'close', this));
  192. topology.on('parseError', createListener(this, 'parseError', this));
  193. topology.once('open', createListener(this, 'open', this));
  194. topology.once('fullsetup', createListener(this, 'fullsetup', this));
  195. topology.once('all', createListener(this, 'all', this));
  196. topology.on('reconnect', createListener(this, 'reconnect', this));
  197. }
  198. inherits(Db, EventEmitter);
  199. Db.prototype.on = deprecate(function() {
  200. return Db.super_.prototype.on.apply(this, arguments);
  201. }, 'Listening to events on the Db class has been deprecated and will be removed in the next major version.');
  202. Db.prototype.once = deprecate(function() {
  203. return Db.super_.prototype.once.apply(this, arguments);
  204. }, 'Listening to events on the Db class has been deprecated and will be removed in the next major version.');
  205. // Topology
  206. Object.defineProperty(Db.prototype, 'topology', {
  207. enumerable: true,
  208. get: function() {
  209. return this.s.topology;
  210. }
  211. });
  212. // Options
  213. Object.defineProperty(Db.prototype, 'options', {
  214. enumerable: true,
  215. get: function() {
  216. return this.s.options;
  217. }
  218. });
  219. // slaveOk specified
  220. Object.defineProperty(Db.prototype, 'slaveOk', {
  221. enumerable: true,
  222. get: function() {
  223. if (
  224. this.s.options.readPreference != null &&
  225. (this.s.options.readPreference !== 'primary' ||
  226. this.s.options.readPreference.mode !== 'primary')
  227. ) {
  228. return true;
  229. }
  230. return false;
  231. }
  232. });
  233. Object.defineProperty(Db.prototype, 'readConcern', {
  234. enumerable: true,
  235. get: function() {
  236. return this.s.readConcern;
  237. }
  238. });
  239. Object.defineProperty(Db.prototype, 'readPreference', {
  240. enumerable: true,
  241. get: function() {
  242. if (this.s.readPreference == null) {
  243. // TODO: check client
  244. return ReadPreference.primary;
  245. }
  246. return this.s.readPreference;
  247. }
  248. });
  249. // get the write Concern
  250. Object.defineProperty(Db.prototype, 'writeConcern', {
  251. enumerable: true,
  252. get: function() {
  253. return this.s.writeConcern;
  254. }
  255. });
  256. Object.defineProperty(Db.prototype, 'namespace', {
  257. enumerable: true,
  258. get: function() {
  259. return this.s.namespace.toString();
  260. }
  261. });
  262. /**
  263. * Execute a command
  264. * @method
  265. * @param {object} command The command hash
  266. * @param {object} [options] Optional settings.
  267. * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  268. * @param {ClientSession} [options.session] optional session to use for this operation
  269. * @param {Db~resultCallback} [callback] The command result callback
  270. * @return {Promise} returns Promise if no callback passed
  271. */
  272. Db.prototype.command = function(command, options, callback) {
  273. if (typeof options === 'function') (callback = options), (options = {});
  274. options = Object.assign({}, options);
  275. const commandOperation = new RunCommandOperation(this, command, options);
  276. return executeOperation(this.s.topology, commandOperation, callback);
  277. };
  278. /**
  279. * Execute an aggregation framework pipeline against the database, needs MongoDB >= 3.6
  280. * @method
  281. * @param {object} [pipeline=[]] Array containing all the aggregation framework commands for the execution.
  282. * @param {object} [options] Optional settings.
  283. * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  284. * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.
  285. * @param {object} [options.cursor] Return the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor.
  286. * @param {number} [options.cursor.batchSize=1000] Deprecated. Use `options.batchSize`
  287. * @param {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [options.explain] The verbosity mode for the explain output.
  288. * @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 >).
  289. * @param {number} [options.maxTimeMS] maxTimeMS specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point.
  290. * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query.
  291. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
  292. * @param {boolean} [options.raw=false] Return document results as raw BSON buffers.
  293. * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution.
  294. * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types.
  295. * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers.
  296. * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
  297. * @param {string} [options.comment] Add a comment to an aggregation command
  298. * @param {string|object} [options.hint] Add an index selection hint to an aggregation command
  299. * @param {ClientSession} [options.session] optional session to use for this operation
  300. * @param {Database~aggregationCallback} callback The command result callback
  301. * @return {(null|AggregationCursor)}
  302. */
  303. Db.prototype.aggregate = function(pipeline, options, callback) {
  304. if (typeof options === 'function') {
  305. callback = options;
  306. options = {};
  307. }
  308. // If we have no options or callback we are doing
  309. // a cursor based aggregation
  310. if (options == null && callback == null) {
  311. options = {};
  312. }
  313. const cursor = new AggregationCursor(
  314. this.s.topology,
  315. new AggregateOperation(this, pipeline, options),
  316. options
  317. );
  318. // TODO: remove this when NODE-2074 is resolved
  319. if (typeof callback === 'function') {
  320. callback(null, cursor);
  321. return;
  322. }
  323. return cursor;
  324. };
  325. /**
  326. * Return the Admin db instance
  327. * @method
  328. * @return {Admin} return the new Admin db instance
  329. */
  330. Db.prototype.admin = function() {
  331. const Admin = require('./admin');
  332. return new Admin(this, this.s.topology, this.s.promiseLibrary);
  333. };
  334. /**
  335. * The callback format for the collection method, must be used if strict is specified
  336. * @callback Db~collectionResultCallback
  337. * @param {MongoError} error An error instance representing the error during the execution.
  338. * @param {Collection} collection The collection instance.
  339. */
  340. /**
  341. * The callback format for an aggregation call
  342. * @callback Database~aggregationCallback
  343. * @param {MongoError} error An error instance representing the error during the execution.
  344. * @param {AggregationCursor} cursor The cursor if the aggregation command was executed successfully.
  345. */
  346. const COLLECTION_OPTION_KEYS = [
  347. 'pkFactory',
  348. 'readPreference',
  349. 'serializeFunctions',
  350. 'strict',
  351. 'readConcern',
  352. 'ignoreUndefined',
  353. 'promoteValues',
  354. 'promoteBuffers',
  355. 'promoteLongs'
  356. ];
  357. /**
  358. * Fetch a specific collection (containing the actual collection information). If the application does not use strict mode you
  359. * can use it without a callback in the following way: `const collection = db.collection('mycollection');`
  360. *
  361. * @method
  362. * @param {string} name the collection name we wish to access.
  363. * @param {object} [options] Optional settings.
  364. * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead.
  365. * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead.
  366. * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead.
  367. * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings.
  368. * @param {boolean} [options.raw=false] Return document results as raw BSON buffers.
  369. * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys.
  370. * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  371. * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
  372. * @param {boolean} [options.strict=false] Returns an error if the collection does not exist
  373. * @param {object} [options.readConcern] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported)
  374. * @param {ReadConcernLevel} [options.readConcern.level='local'] Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported)
  375. * @param {Db~collectionResultCallback} [callback] The collection result callback
  376. * @return {Collection} return the new Collection instance if not in strict mode
  377. */
  378. Db.prototype.collection = function(name, options, callback) {
  379. if (typeof options === 'function') (callback = options), (options = {});
  380. options = options || {};
  381. options = Object.assign({}, options);
  382. // Set the promise library
  383. options.promiseLibrary = this.s.promiseLibrary;
  384. // If we have not set a collection level readConcern set the db level one
  385. options.readConcern = options.readConcern
  386. ? new ReadConcern(options.readConcern.level)
  387. : this.readConcern;
  388. // Do we have ignoreUndefined set
  389. if (this.s.options.ignoreUndefined) {
  390. options.ignoreUndefined = this.s.options.ignoreUndefined;
  391. }
  392. for (const collectionOptionKey of COLLECTION_OPTION_KEYS) {
  393. if (!(collectionOptionKey in options) && this.s.options[collectionOptionKey] !== undefined) {
  394. options[collectionOptionKey] = this.s.options[collectionOptionKey];
  395. }
  396. }
  397. // Merge in all needed options and ensure correct writeConcern merging from db level
  398. options = conditionallyMergeWriteConcern(options, this.s.options);
  399. // Execute
  400. if (options == null || !options.strict) {
  401. try {
  402. const collection = new Collection(
  403. this,
  404. this.s.topology,
  405. this.databaseName,
  406. name,
  407. this.s.pkFactory,
  408. options
  409. );
  410. if (callback) callback(null, collection);
  411. return collection;
  412. } catch (err) {
  413. if (err instanceof MongoError && callback) return callback(err);
  414. throw err;
  415. }
  416. }
  417. // Strict mode
  418. if (typeof callback !== 'function') {
  419. throw toError(`A callback is required in strict mode. While getting collection ${name}`);
  420. }
  421. // Did the user destroy the topology
  422. if (this.serverConfig && this.serverConfig.isDestroyed()) {
  423. return callback(new MongoError('topology was destroyed'));
  424. }
  425. const listCollectionOptions = Object.assign({}, options, { nameOnly: true });
  426. // Strict mode
  427. this.listCollections({ name: name }, listCollectionOptions).toArray((err, collections) => {
  428. if (err != null) return handleCallback(callback, err, null);
  429. if (collections.length === 0)
  430. return handleCallback(
  431. callback,
  432. toError(`Collection ${name} does not exist. Currently in strict mode.`),
  433. null
  434. );
  435. try {
  436. return handleCallback(
  437. callback,
  438. null,
  439. new Collection(this, this.s.topology, this.databaseName, name, this.s.pkFactory, options)
  440. );
  441. } catch (err) {
  442. return handleCallback(callback, err, null);
  443. }
  444. });
  445. };
  446. /**
  447. * Create a new collection on a server with the specified options. Use this to create capped collections.
  448. * More information about command options available at https://docs.mongodb.com/manual/reference/command/create/
  449. *
  450. * @method
  451. * @param {string} name the collection name we wish to access.
  452. * @param {object} [options] Optional settings.
  453. * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead.
  454. * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead.
  455. * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead.
  456. * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings.
  457. * @param {boolean} [options.raw=false] Return document results as raw BSON buffers.
  458. * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys.
  459. * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  460. * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
  461. * @param {boolean} [options.strict=false] DEPRECATED: Returns an error if the collection does not exist
  462. * @param {boolean} [options.capped=false] Create a capped collection.
  463. * @param {boolean} [options.autoIndexId=true] DEPRECATED: Create an index on the _id field of the document, True by default on MongoDB 2.6 - 3.0
  464. * @param {number} [options.size] The size of the capped collection in bytes.
  465. * @param {number} [options.max] The maximum number of documents in the capped collection.
  466. * @param {number} [options.flags] Optional. Available for the MMAPv1 storage engine only to set the usePowerOf2Sizes and the noPadding flag.
  467. * @param {object} [options.storageEngine] Allows users to specify configuration to the storage engine on a per-collection basis when creating a collection on MongoDB 3.0 or higher.
  468. * @param {object} [options.validator] Allows users to specify validation rules or expressions for the collection. For more information, see Document Validation on MongoDB 3.2 or higher.
  469. * @param {string} [options.validationLevel] Determines how strictly MongoDB applies the validation rules to existing documents during an update on MongoDB 3.2 or higher.
  470. * @param {string} [options.validationAction] Determines whether to error on invalid documents or just warn about the violations but allow invalid documents to be inserted on MongoDB 3.2 or higher.
  471. * @param {object} [options.indexOptionDefaults] Allows users to specify a default configuration for indexes when creating a collection on MongoDB 3.2 or higher.
  472. * @param {string} [options.viewOn] The name of the source collection or view from which to create the view. The name is not the full namespace of the collection or view; i.e. does not include the database name and implies the same database as the view to create on MongoDB 3.4 or higher.
  473. * @param {array} [options.pipeline] An array that consists of the aggregation pipeline stage. Creates the view by applying the specified pipeline to the viewOn collection or view on MongoDB 3.4 or higher.
  474. * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
  475. * @param {ClientSession} [options.session] optional session to use for this operation
  476. * @param {Db~collectionResultCallback} [callback] The results callback
  477. * @return {Promise} returns Promise if no callback passed
  478. */
  479. Db.prototype.createCollection = deprecateOptions(
  480. {
  481. name: 'Db.createCollection',
  482. deprecatedOptions: ['autoIndexId', 'strict', 'w', 'wtimeout', 'j'],
  483. optionsIndex: 1
  484. },
  485. function(name, options, callback) {
  486. if (typeof options === 'function') (callback = options), (options = {});
  487. options = options || {};
  488. options.promiseLibrary = options.promiseLibrary || this.s.promiseLibrary;
  489. options.readConcern = options.readConcern
  490. ? new ReadConcern(options.readConcern.level)
  491. : this.readConcern;
  492. const createCollectionOperation = new CreateCollectionOperation(this, name, options);
  493. return executeOperation(this.s.topology, createCollectionOperation, callback);
  494. }
  495. );
  496. /**
  497. * Get all the db statistics.
  498. *
  499. * @method
  500. * @param {object} [options] Optional settings.
  501. * @param {number} [options.scale] Divide the returned sizes by scale value.
  502. * @param {ClientSession} [options.session] optional session to use for this operation
  503. * @param {Db~resultCallback} [callback] The collection result callback
  504. * @return {Promise} returns Promise if no callback passed
  505. */
  506. Db.prototype.stats = function(options, callback) {
  507. if (typeof options === 'function') (callback = options), (options = {});
  508. options = options || {};
  509. // Build command object
  510. const commandObject = { dbStats: true };
  511. // Check if we have the scale value
  512. if (options['scale'] != null) commandObject['scale'] = options['scale'];
  513. // If we have a readPreference set
  514. if (options.readPreference == null && this.s.readPreference) {
  515. options.readPreference = this.s.readPreference;
  516. }
  517. const statsOperation = new CommandOperation(this, options, null, commandObject);
  518. // Execute the command
  519. return executeOperation(this.s.topology, statsOperation, callback);
  520. };
  521. /**
  522. * Get the list of all collection information for the specified db.
  523. *
  524. * @method
  525. * @param {object} [filter={}] Query to filter collections by
  526. * @param {object} [options] Optional settings.
  527. * @param {boolean} [options.nameOnly=false] Since 4.0: If true, will only return the collection name in the response, and will omit additional info
  528. * @param {number} [options.batchSize=1000] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection
  529. * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  530. * @param {ClientSession} [options.session] optional session to use for this operation
  531. * @return {CommandCursor}
  532. */
  533. Db.prototype.listCollections = function(filter, options) {
  534. filter = filter || {};
  535. options = options || {};
  536. return new CommandCursor(
  537. this.s.topology,
  538. new ListCollectionsOperation(this, filter, options),
  539. options
  540. );
  541. };
  542. /**
  543. * Evaluate JavaScript on the server
  544. *
  545. * @method
  546. * @param {Code} code JavaScript to execute on server.
  547. * @param {(object|array)} parameters The parameters for the call.
  548. * @param {object} [options] Optional settings.
  549. * @param {boolean} [options.nolock=false] Tell MongoDB not to block on the evaluation of the javascript.
  550. * @param {ClientSession} [options.session] optional session to use for this operation
  551. * @param {Db~resultCallback} [callback] The results callback
  552. * @deprecated Eval is deprecated on MongoDB 3.2 and forward
  553. * @return {Promise} returns Promise if no callback passed
  554. */
  555. Db.prototype.eval = deprecate(function(code, parameters, options, callback) {
  556. const args = Array.prototype.slice.call(arguments, 1);
  557. callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
  558. parameters = args.length ? args.shift() : parameters;
  559. options = args.length ? args.shift() || {} : {};
  560. return executeLegacyOperation(this.s.topology, evaluate, [
  561. this,
  562. code,
  563. parameters,
  564. options,
  565. callback
  566. ]);
  567. }, 'Db.eval is deprecated as of MongoDB version 3.2');
  568. /**
  569. * Rename a collection.
  570. *
  571. * @method
  572. * @param {string} fromCollection Name of current collection to rename.
  573. * @param {string} toCollection New name of of the collection.
  574. * @param {object} [options] Optional settings.
  575. * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists.
  576. * @param {ClientSession} [options.session] optional session to use for this operation
  577. * @param {Db~collectionResultCallback} [callback] The results callback
  578. * @return {Promise} returns Promise if no callback passed
  579. */
  580. Db.prototype.renameCollection = function(fromCollection, toCollection, options, callback) {
  581. if (typeof options === 'function') (callback = options), (options = {});
  582. options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY });
  583. // Add return new collection
  584. options.new_collection = true;
  585. const renameOperation = new RenameOperation(
  586. this.collection(fromCollection),
  587. toCollection,
  588. options
  589. );
  590. return executeOperation(this.s.topology, renameOperation, callback);
  591. };
  592. /**
  593. * Drop a collection from the database, removing it permanently. New accesses will create a new collection.
  594. *
  595. * @method
  596. * @param {string} name Name of collection to drop
  597. * @param {Object} [options] Optional settings
  598. * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead.
  599. * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead.
  600. * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead.
  601. * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings.
  602. * @param {ClientSession} [options.session] optional session to use for this operation
  603. * @param {Db~resultCallback} [callback] The results callback
  604. * @return {Promise} returns Promise if no callback passed
  605. */
  606. Db.prototype.dropCollection = function(name, options, callback) {
  607. if (typeof options === 'function') (callback = options), (options = {});
  608. options = options || {};
  609. const dropCollectionOperation = new DropCollectionOperation(this, name, options);
  610. return executeOperation(this.s.topology, dropCollectionOperation, callback);
  611. };
  612. /**
  613. * Drop a database, removing it permanently from the server.
  614. *
  615. * @method
  616. * @param {Object} [options] Optional settings
  617. * @param {ClientSession} [options.session] optional session to use for this operation
  618. * @param {Db~resultCallback} [callback] The results callback
  619. * @return {Promise} returns Promise if no callback passed
  620. */
  621. Db.prototype.dropDatabase = function(options, callback) {
  622. if (typeof options === 'function') (callback = options), (options = {});
  623. options = options || {};
  624. const dropDatabaseOperation = new DropDatabaseOperation(this, options);
  625. return executeOperation(this.s.topology, dropDatabaseOperation, callback);
  626. };
  627. /**
  628. * Fetch all collections for the current db.
  629. *
  630. * @method
  631. * @param {Object} [options] Optional settings
  632. * @param {ClientSession} [options.session] optional session to use for this operation
  633. * @param {Db~collectionsResultCallback} [callback] The results callback
  634. * @return {Promise} returns Promise if no callback passed
  635. */
  636. Db.prototype.collections = function(options, callback) {
  637. if (typeof options === 'function') (callback = options), (options = {});
  638. options = options || {};
  639. const collectionsOperation = new CollectionsOperation(this, options);
  640. return executeOperation(this.s.topology, collectionsOperation, callback);
  641. };
  642. /**
  643. * Runs a command on the database as admin.
  644. * @method
  645. * @param {object} command The command hash
  646. * @param {object} [options] Optional settings.
  647. * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  648. * @param {ClientSession} [options.session] optional session to use for this operation
  649. * @param {Db~resultCallback} [callback] The command result callback
  650. * @return {Promise} returns Promise if no callback passed
  651. */
  652. Db.prototype.executeDbAdminCommand = function(selector, options, callback) {
  653. if (typeof options === 'function') (callback = options), (options = {});
  654. options = options || {};
  655. options.readPreference = ReadPreference.resolve(this, options);
  656. const executeDbAdminCommandOperation = new ExecuteDbAdminCommandOperation(
  657. this,
  658. selector,
  659. options
  660. );
  661. return executeOperation(this.s.topology, executeDbAdminCommandOperation, callback);
  662. };
  663. /**
  664. * Creates an index on the db and collection.
  665. * @method
  666. * @param {string} name Name of the collection to create the index on.
  667. * @param {(string|object)} fieldOrSpec Defines the index.
  668. * @param {object} [options] Optional settings.
  669. * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead.
  670. * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead.
  671. * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead.
  672. * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings.
  673. * @param {boolean} [options.unique=false] Creates an unique index.
  674. * @param {boolean} [options.sparse=false] Creates a sparse index.
  675. * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible.
  676. * @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
  677. * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates.
  678. * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates.
  679. * @param {number} [options.v] Specify the format version of the indexes.
  680. * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)
  681. * @param {string} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes)
  682. * @param {object} [options.partialFilterExpression] Creates a partial index based on the given filter object (MongoDB 3.2 or higher)
  683. * @param {ClientSession} [options.session] optional session to use for this operation
  684. * @param {(number|string)} [options.commitQuorum] (MongoDB 4.4. or higher) Specifies how many data-bearing members of a replica set, including the primary, must complete the index builds successfully before the primary marks the indexes as ready. This option accepts the same values for the "w" field in a write concern plus "votingMembers", which indicates all voting data-bearing nodes.
  685. * @param {Db~resultCallback} [callback] The command result callback
  686. * @return {Promise} returns Promise if no callback passed
  687. */
  688. Db.prototype.createIndex = function(name, fieldOrSpec, options, callback) {
  689. if (typeof options === 'function') (callback = options), (options = {});
  690. options = options ? Object.assign({}, options) : {};
  691. const createIndexesOperation = new CreateIndexesOperation(this, name, fieldOrSpec, options);
  692. return executeOperation(this.s.topology, createIndexesOperation, callback);
  693. };
  694. /**
  695. * Ensures that an index exists, if it does not it creates it
  696. * @method
  697. * @deprecated since version 2.0
  698. * @param {string} name The index name
  699. * @param {(string|object)} fieldOrSpec Defines the index.
  700. * @param {object} [options] Optional settings.
  701. * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead.
  702. * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead.
  703. * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead.
  704. * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings.
  705. * @param {boolean} [options.unique=false] Creates an unique index.
  706. * @param {boolean} [options.sparse=false] Creates a sparse index.
  707. * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible.
  708. * @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
  709. * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates.
  710. * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates.
  711. * @param {number} [options.v] Specify the format version of the indexes.
  712. * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)
  713. * @param {number} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes)
  714. * @param {ClientSession} [options.session] optional session to use for this operation
  715. * @param {Db~resultCallback} [callback] The command result callback
  716. * @return {Promise} returns Promise if no callback passed
  717. */
  718. Db.prototype.ensureIndex = deprecate(function(name, fieldOrSpec, options, callback) {
  719. if (typeof options === 'function') (callback = options), (options = {});
  720. options = options || {};
  721. return executeLegacyOperation(this.s.topology, ensureIndex, [
  722. this,
  723. name,
  724. fieldOrSpec,
  725. options,
  726. callback
  727. ]);
  728. }, 'Db.ensureIndex is deprecated as of MongoDB version 3.0 / driver version 2.0');
  729. Db.prototype.addChild = function(db) {
  730. if (this.s.parentDb) return this.s.parentDb.addChild(db);
  731. this.s.children.push(db);
  732. };
  733. /**
  734. * Add a user to the database.
  735. * @method
  736. * @param {string} username The username.
  737. * @param {string} password The password.
  738. * @param {object} [options] Optional settings.
  739. * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead.
  740. * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead.
  741. * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead.
  742. * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings.
  743. * @param {object} [options.customData] Custom data associated with the user (only Mongodb 2.6 or higher)
  744. * @param {object[]} [options.roles] Roles associated with the created user (only Mongodb 2.6 or higher)
  745. * @param {ClientSession} [options.session] optional session to use for this operation
  746. * @param {Db~resultCallback} [callback] The command result callback
  747. * @return {Promise} returns Promise if no callback passed
  748. */
  749. Db.prototype.addUser = function(username, password, options, callback) {
  750. if (typeof options === 'function') (callback = options), (options = {});
  751. options = options || {};
  752. // Special case where there is no password ($external users)
  753. if (typeof username === 'string' && password != null && typeof password === 'object') {
  754. options = password;
  755. password = null;
  756. }
  757. const addUserOperation = new AddUserOperation(this, username, password, options);
  758. return executeOperation(this.s.topology, addUserOperation, callback);
  759. };
  760. /**
  761. * Remove a user from a database
  762. * @method
  763. * @param {string} username The username.
  764. * @param {object} [options] Optional settings.
  765. * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead.
  766. * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead.
  767. * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead.
  768. * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings.
  769. * @param {ClientSession} [options.session] optional session to use for this operation
  770. * @param {Db~resultCallback} [callback] The command result callback
  771. * @return {Promise} returns Promise if no callback passed
  772. */
  773. Db.prototype.removeUser = function(username, options, callback) {
  774. if (typeof options === 'function') (callback = options), (options = {});
  775. options = options || {};
  776. const removeUserOperation = new RemoveUserOperation(this, username, options);
  777. return executeOperation(this.s.topology, removeUserOperation, callback);
  778. };
  779. /**
  780. * Set the current profiling level of MongoDB
  781. *
  782. * @param {string} level The new profiling level (off, slow_only, all).
  783. * @param {Object} [options] Optional settings
  784. * @param {ClientSession} [options.session] optional session to use for this operation
  785. * @param {Db~resultCallback} [callback] The command result callback.
  786. * @return {Promise} returns Promise if no callback passed
  787. */
  788. Db.prototype.setProfilingLevel = function(level, options, callback) {
  789. if (typeof options === 'function') (callback = options), (options = {});
  790. options = options || {};
  791. const setProfilingLevelOperation = new SetProfilingLevelOperation(this, level, options);
  792. return executeOperation(this.s.topology, setProfilingLevelOperation, callback);
  793. };
  794. /**
  795. * Retrieve the current profiling information for MongoDB
  796. *
  797. * @param {Object} [options] Optional settings
  798. * @param {ClientSession} [options.session] optional session to use for this operation
  799. * @param {Db~resultCallback} [callback] The command result callback.
  800. * @return {Promise} returns Promise if no callback passed
  801. * @deprecated Query the system.profile collection directly.
  802. */
  803. Db.prototype.profilingInfo = deprecate(function(options, callback) {
  804. if (typeof options === 'function') (callback = options), (options = {});
  805. options = options || {};
  806. return executeLegacyOperation(this.s.topology, profilingInfo, [this, options, callback]);
  807. }, 'Db.profilingInfo is deprecated. Query the system.profile collection directly.');
  808. /**
  809. * Retrieve the current profiling Level for MongoDB
  810. *
  811. * @param {Object} [options] Optional settings
  812. * @param {ClientSession} [options.session] optional session to use for this operation
  813. * @param {Db~resultCallback} [callback] The command result callback
  814. * @return {Promise} returns Promise if no callback passed
  815. */
  816. Db.prototype.profilingLevel = function(options, callback) {
  817. if (typeof options === 'function') (callback = options), (options = {});
  818. options = options || {};
  819. const profilingLevelOperation = new ProfilingLevelOperation(this, options);
  820. return executeOperation(this.s.topology, profilingLevelOperation, callback);
  821. };
  822. /**
  823. * Retrieves this collections index info.
  824. * @method
  825. * @param {string} name The name of the collection.
  826. * @param {object} [options] Optional settings.
  827. * @param {boolean} [options.full=false] Returns the full raw index information.
  828. * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  829. * @param {ClientSession} [options.session] optional session to use for this operation
  830. * @param {Db~resultCallback} [callback] The command result callback
  831. * @return {Promise} returns Promise if no callback passed
  832. */
  833. Db.prototype.indexInformation = function(name, options, callback) {
  834. if (typeof options === 'function') (callback = options), (options = {});
  835. options = options || {};
  836. const indexInformationOperation = new IndexInformationOperation(this, name, options);
  837. return executeOperation(this.s.topology, indexInformationOperation, callback);
  838. };
  839. /**
  840. * Unref all sockets
  841. * @method
  842. */
  843. Db.prototype.unref = function() {
  844. this.s.topology.unref();
  845. };
  846. /**
  847. * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this database. Will ignore all changes to system collections.
  848. * @method
  849. * @since 3.1.0
  850. * @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents.
  851. * @param {object} [options] Optional settings
  852. * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred.
  853. * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document.
  854. * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query
  855. * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.
  856. * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.
  857. * @param {ReadPreference} [options.readPreference] The read preference. Defaults to the read preference of the database. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}.
  858. * @param {Timestamp} [options.startAtOperationTime] receive change events that occur after the specified timestamp
  859. * @param {ClientSession} [options.session] optional session to use for this operation
  860. * @return {ChangeStream} a ChangeStream instance.
  861. */
  862. Db.prototype.watch = function(pipeline, options) {
  863. pipeline = pipeline || [];
  864. options = options || {};
  865. // Allow optionally not specifying a pipeline
  866. if (!Array.isArray(pipeline)) {
  867. options = pipeline;
  868. pipeline = [];
  869. }
  870. return new ChangeStream(this, pipeline, options);
  871. };
  872. /**
  873. * Return the db logger
  874. * @method
  875. * @return {Logger} return the db logger
  876. * @ignore
  877. */
  878. Db.prototype.getLogger = function() {
  879. return this.s.logger;
  880. };
  881. /**
  882. * Db close event
  883. *
  884. * Emitted after a socket closed against a single server or mongos proxy.
  885. *
  886. * @event Db#close
  887. * @type {MongoError}
  888. */
  889. /**
  890. * Db reconnect event
  891. *
  892. * * Server: Emitted when the driver has reconnected and re-authenticated.
  893. * * ReplicaSet: N/A
  894. * * Mongos: Emitted when the driver reconnects and re-authenticates successfully against a Mongos.
  895. *
  896. * @event Db#reconnect
  897. * @type {object}
  898. */
  899. /**
  900. * Db error event
  901. *
  902. * Emitted after an error occurred against a single server or mongos proxy.
  903. *
  904. * @event Db#error
  905. * @type {MongoError}
  906. */
  907. /**
  908. * Db timeout event
  909. *
  910. * Emitted after a socket timeout occurred against a single server or mongos proxy.
  911. *
  912. * @event Db#timeout
  913. * @type {MongoError}
  914. */
  915. /**
  916. * Db parseError event
  917. *
  918. * The parseError event is emitted if the driver detects illegal or corrupt BSON being received from the server.
  919. *
  920. * @event Db#parseError
  921. * @type {MongoError}
  922. */
  923. /**
  924. * Db fullsetup event, emitted when all servers in the topology have been connected to at start up time.
  925. *
  926. * * Server: Emitted when the driver has connected to the single server and has authenticated.
  927. * * ReplSet: Emitted after the driver has attempted to connect to all replicaset members.
  928. * * Mongos: Emitted after the driver has attempted to connect to all mongos proxies.
  929. *
  930. * @event Db#fullsetup
  931. * @type {Db}
  932. */
  933. // Constants
  934. Db.SYSTEM_NAMESPACE_COLLECTION = CONSTANTS.SYSTEM_NAMESPACE_COLLECTION;
  935. Db.SYSTEM_INDEX_COLLECTION = CONSTANTS.SYSTEM_INDEX_COLLECTION;
  936. Db.SYSTEM_PROFILE_COLLECTION = CONSTANTS.SYSTEM_PROFILE_COLLECTION;
  937. Db.SYSTEM_USER_COLLECTION = CONSTANTS.SYSTEM_USER_COLLECTION;
  938. Db.SYSTEM_COMMAND_COLLECTION = CONSTANTS.SYSTEM_COMMAND_COLLECTION;
  939. Db.SYSTEM_JS_COLLECTION = CONSTANTS.SYSTEM_JS_COLLECTION;
  940. module.exports = Db;