db.js 48 KB

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