mongo_client.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. 'use strict';
  2. const ChangeStream = require('./change_stream');
  3. const Db = require('./db');
  4. const EventEmitter = require('events').EventEmitter;
  5. const executeOperation = require('./utils').executeOperation;
  6. const handleCallback = require('./utils').handleCallback;
  7. const inherits = require('util').inherits;
  8. const MongoError = require('mongodb-core').MongoError;
  9. // Operations
  10. const connectOp = require('./operations/mongo_client_ops').connectOp;
  11. const logout = require('./operations/mongo_client_ops').logout;
  12. const validOptions = require('./operations/mongo_client_ops').validOptions;
  13. /**
  14. * @fileOverview The **MongoClient** class is a class that allows for making Connections to MongoDB.
  15. *
  16. * @example
  17. * // Connect using a MongoClient instance
  18. * const MongoClient = require('mongodb').MongoClient;
  19. * const test = require('assert');
  20. * // Connection url
  21. * const url = 'mongodb://localhost:27017';
  22. * // Database Name
  23. * const dbName = 'test';
  24. * // Connect using MongoClient
  25. * const mongoClient = new MongoClient(url);
  26. * mongoClient.connect(function(err, client) {
  27. * const db = client.db(dbName);
  28. * client.close();
  29. * });
  30. *
  31. * @example
  32. * // Connect using the MongoClient.connect static method
  33. * const MongoClient = require('mongodb').MongoClient;
  34. * const test = require('assert');
  35. * // Connection url
  36. * const url = 'mongodb://localhost:27017';
  37. * // Database Name
  38. * const dbName = 'test';
  39. * // Connect using MongoClient
  40. * MongoClient.connect(url, function(err, client) {
  41. * const db = client.db(dbName);
  42. * client.close();
  43. * });
  44. */
  45. /**
  46. * Creates a new MongoClient instance
  47. * @class
  48. * @param {string} url The connection URI string
  49. * @param {object} [options] Optional settings
  50. * @param {number} [options.poolSize=5] The maximum size of the individual server pool
  51. * @param {boolean} [options.ssl=false] Enable SSL connection.
  52. * @param {boolean} [options.sslValidate=true] Validate mongod server certificate against Certificate Authority
  53. * @param {buffer} [options.sslCA=undefined] SSL Certificate store binary buffer
  54. * @param {buffer} [options.sslCert=undefined] SSL Certificate binary buffer
  55. * @param {buffer} [options.sslKey=undefined] SSL Key file binary buffer
  56. * @param {string} [options.sslPass=undefined] SSL Certificate pass phrase
  57. * @param {buffer} [options.sslCRL=undefined] SSL Certificate revocation list binary buffer
  58. * @param {boolean} [options.autoReconnect=true] Enable autoReconnect for single server instances
  59. * @param {boolean} [options.noDelay=true] TCP Connection no delay
  60. * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled
  61. * @param {number} [options.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket
  62. * @param {number} [options.connectTimeoutMS=30000] TCP Connection timeout setting
  63. * @param {number} [options.family] Version of IP stack. Can be 4, 6 or null (default).
  64. * If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure
  65. * @param {number} [options.socketTimeoutMS=360000] TCP Socket timeout setting
  66. * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times
  67. * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries
  68. * @param {boolean} [options.ha=true] Control if high availability monitoring runs for Replicaset or Mongos proxies
  69. * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry
  70. * @param {string} [options.replicaSet=undefined] The Replicaset set name
  71. * @param {number} [options.secondaryAcceptableLatencyMS=15] Cutoff latency point in MS for Replicaset member selection
  72. * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for Mongos proxies selection
  73. * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available
  74. * @param {string} [options.authSource=undefined] Define the database to authenticate against
  75. * @param {(number|string)} [options.w] The write concern
  76. * @param {number} [options.wtimeout] The write concern timeout
  77. * @param {boolean} [options.j=false] Specify a journal write concern
  78. * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver
  79. * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object
  80. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields
  81. * @param {boolean} [options.raw=false] Return document results as raw BSON buffers
  82. * @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
  83. * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST)
  84. * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys
  85. * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible
  86. * @param {object} [options.readConcern] Specify a read concern for the collection (only MongoDB 3.2 or higher supported)
  87. * @param {string} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported)
  88. * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed)
  89. * @param {string} [options.loggerLevel=undefined] The logging level (error/warn/info/debug)
  90. * @param {object} [options.logger=undefined] Custom logger object
  91. * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types
  92. * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers
  93. * @param {boolean} [options.promoteLongs=true] Promotes long values to number if they fit inside the 53 bits resolution
  94. * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit
  95. * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function
  96. * @param {object} [options.validateOptions=false] Validate MongoClient passed in options for correctness
  97. * @param {string} [options.appname=undefined] The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections
  98. * @param {string} [options.auth.user=undefined] The username for auth
  99. * @param {string} [options.auth.password=undefined] The password for auth
  100. * @param {string} [options.authMechanism=undefined] Mechanism for authentication: MDEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1
  101. * @param {object} [options.compression] Type of compression to use: snappy or zlib
  102. * @param {boolean} [options.fsync=false] Specify a file sync write concern
  103. * @param {array} [options.readPreferenceTags] Read preference tags
  104. * @param {number} [options.numberOfRetries=5] The number of retries for a tailable cursor
  105. * @param {boolean} [options.auto_reconnect=true] Enable auto reconnecting for single server instances
  106. * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this client
  107. * @param {number} [options.minSize] If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections
  108. * @param {boolean} [options.useNewUrlParser=false] Determines whether or not to use the new url parser. Enables the new, spec-compliant, url parser shipped in the core driver. This url parser fixes a number of problems with the original parser, and aims to outright replace that parser in the near future.
  109. * @param {MongoClient~connectCallback} [callback] The command result callback
  110. * @return {MongoClient} a MongoClient instance
  111. */
  112. function MongoClient(url, options) {
  113. if (!(this instanceof MongoClient)) return new MongoClient(url, options);
  114. // Set up event emitter
  115. EventEmitter.call(this);
  116. // The internal state
  117. this.s = {
  118. url: url,
  119. options: options || {},
  120. promiseLibrary: null,
  121. dbCache: {},
  122. sessions: []
  123. };
  124. // Get the promiseLibrary
  125. const promiseLibrary = this.s.options.promiseLibrary || Promise;
  126. // Add the promise to the internal state
  127. this.s.promiseLibrary = promiseLibrary;
  128. }
  129. /**
  130. * @ignore
  131. */
  132. inherits(MongoClient, EventEmitter);
  133. /**
  134. * The callback format for results
  135. * @callback MongoClient~connectCallback
  136. * @param {MongoError} error An error instance representing the error during the execution.
  137. * @param {MongoClient} client The connected client.
  138. */
  139. /**
  140. * Connect to MongoDB using a url as documented at
  141. *
  142. * docs.mongodb.org/manual/reference/connection-string/
  143. *
  144. * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver
  145. *
  146. * @method
  147. * @param {MongoClient~connectCallback} [callback] The command result callback
  148. * @return {Promise<MongoClient>} returns Promise if no callback passed
  149. */
  150. MongoClient.prototype.connect = function(callback) {
  151. // Validate options object
  152. const err = validOptions(this.s.options);
  153. if (typeof callback === 'string') {
  154. throw new TypeError('`connect` only accepts a callback');
  155. }
  156. return executeOperation(this, connectOp, [this, err, callback], {
  157. skipSessions: true
  158. });
  159. };
  160. /**
  161. * Logout user from server, fire off on all connections and remove all auth info
  162. * @method
  163. * @param {object} [options] Optional settings.
  164. * @param {string} [options.dbName] Logout against different database than current.
  165. * @param {Db~resultCallback} [callback] The command result callback
  166. * @return {Promise} returns Promise if no callback passed
  167. */
  168. MongoClient.prototype.logout = function(options, callback) {
  169. if (typeof options === 'function') (callback = options), (options = {});
  170. options = options || {};
  171. // Establish the correct database name
  172. const dbName = this.s.options.authSource ? this.s.options.authSource : this.s.options.dbName;
  173. return executeOperation(this, logout, [this, dbName, callback], {
  174. skipSessions: true
  175. });
  176. };
  177. /**
  178. * Close the db and its underlying connections
  179. * @method
  180. * @param {boolean} force Force close, emitting no events
  181. * @param {Db~noResultCallback} [callback] The result callback
  182. * @return {Promise} returns Promise if no callback passed
  183. */
  184. MongoClient.prototype.close = function(force, callback) {
  185. if (typeof force === 'function') (callback = force), (force = false);
  186. // Close the topology connection
  187. if (this.topology) {
  188. this.topology.close(force);
  189. }
  190. // Emit close event
  191. this.emit('close', this);
  192. // Fire close event on any cached db instances
  193. for (const name in this.s.dbCache) {
  194. this.s.dbCache[name].emit('close');
  195. }
  196. // Remove listeners after emit
  197. this.removeAllListeners('close');
  198. // Callback after next event loop tick
  199. if (typeof callback === 'function')
  200. return process.nextTick(() => {
  201. handleCallback(callback, null);
  202. });
  203. // Return dummy promise
  204. return new this.s.promiseLibrary(resolve => {
  205. resolve();
  206. });
  207. };
  208. /**
  209. * Create a new Db instance sharing the current socket connections. Be aware that the new db instances are
  210. * related in a parent-child relationship to the original instance so that events are correctly emitted on child
  211. * db instances. Child db instances are cached so performing db('db1') twice will return the same instance.
  212. * You can control these behaviors with the options noListener and returnNonCachedInstance.
  213. *
  214. * @method
  215. * @param {string} [dbName] The name of the database we want to use. If not provided, use database name from connection string.
  216. * @param {object} [options] Optional settings.
  217. * @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection.
  218. * @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created
  219. * @return {Db}
  220. */
  221. MongoClient.prototype.db = function(dbName, options) {
  222. options = options || {};
  223. // Default to db from connection string if not provided
  224. if (!dbName) {
  225. dbName = this.s.options.dbName;
  226. }
  227. // Copy the options and add out internal override of the not shared flag
  228. const finalOptions = Object.assign({}, this.s.options, options);
  229. // Do we have the db in the cache already
  230. if (this.s.dbCache[dbName] && finalOptions.returnNonCachedInstance !== true) {
  231. return this.s.dbCache[dbName];
  232. }
  233. // Add promiseLibrary
  234. finalOptions.promiseLibrary = this.s.promiseLibrary;
  235. // If no topology throw an error message
  236. if (!this.topology) {
  237. throw new MongoError('MongoClient must be connected before calling MongoClient.prototype.db');
  238. }
  239. // Return the db object
  240. const db = new Db(dbName, this.topology, finalOptions);
  241. // Add the db to the cache
  242. this.s.dbCache[dbName] = db;
  243. // Return the database
  244. return db;
  245. };
  246. /**
  247. * Check if MongoClient is connected
  248. *
  249. * @method
  250. * @param {object} [options] Optional settings.
  251. * @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection.
  252. * @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created
  253. * @return {boolean}
  254. */
  255. MongoClient.prototype.isConnected = function(options) {
  256. options = options || {};
  257. if (!this.topology) return false;
  258. return this.topology.isConnected(options);
  259. };
  260. /**
  261. * Connect to MongoDB using a url as documented at
  262. *
  263. * docs.mongodb.org/manual/reference/connection-string/
  264. *
  265. * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver
  266. *
  267. * @method
  268. * @static
  269. * @param {string} url The connection URI string
  270. * @param {object} [options] Optional settings
  271. * @param {number} [options.poolSize=5] The maximum size of the individual server pool
  272. * @param {boolean} [options.ssl=false] Enable SSL connection.
  273. * @param {boolean} [options.sslValidate=true] Validate mongod server certificate against Certificate Authority
  274. * @param {buffer} [options.sslCA=undefined] SSL Certificate store binary buffer
  275. * @param {buffer} [options.sslCert=undefined] SSL Certificate binary buffer
  276. * @param {buffer} [options.sslKey=undefined] SSL Key file binary buffer
  277. * @param {string} [options.sslPass=undefined] SSL Certificate pass phrase
  278. * @param {buffer} [options.sslCRL=undefined] SSL Certificate revocation list binary buffer
  279. * @param {boolean} [options.autoReconnect=true] Enable autoReconnect for single server instances
  280. * @param {boolean} [options.noDelay=true] TCP Connection no delay
  281. * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled
  282. * @param {boolean} [options.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket
  283. * @param {number} [options.connectTimeoutMS=30000] TCP Connection timeout setting
  284. * @param {number} [options.family] Version of IP stack. Can be 4, 6 or null (default).
  285. * If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure
  286. * @param {number} [options.socketTimeoutMS=360000] TCP Socket timeout setting
  287. * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times
  288. * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries
  289. * @param {boolean} [options.ha=true] Control if high availability monitoring runs for Replicaset or Mongos proxies
  290. * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry
  291. * @param {string} [options.replicaSet=undefined] The Replicaset set name
  292. * @param {number} [options.secondaryAcceptableLatencyMS=15] Cutoff latency point in MS for Replicaset member selection
  293. * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for Mongos proxies selection
  294. * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available
  295. * @param {string} [options.authSource=undefined] Define the database to authenticate against
  296. * @param {(number|string)} [options.w] The write concern
  297. * @param {number} [options.wtimeout] The write concern timeout
  298. * @param {boolean} [options.j=false] Specify a journal write concern
  299. * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver
  300. * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object
  301. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields
  302. * @param {boolean} [options.raw=false] Return document results as raw BSON buffers
  303. * @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
  304. * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST)
  305. * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys
  306. * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible
  307. * @param {object} [options.readConcern] Specify a read concern for the collection (only MongoDB 3.2 or higher supported)
  308. * @param {string} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported)
  309. * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed)
  310. * @param {string} [options.loggerLevel=undefined] The logging level (error/warn/info/debug)
  311. * @param {object} [options.logger=undefined] Custom logger object
  312. * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types
  313. * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers
  314. * @param {boolean} [options.promoteLongs=true] Promotes long values to number if they fit inside the 53 bits resolution
  315. * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit
  316. * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function
  317. * @param {object} [options.validateOptions=false] Validate MongoClient passed in options for correctness
  318. * @param {string} [options.appname=undefined] The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections
  319. * @param {string} [options.auth.user=undefined] The username for auth
  320. * @param {string} [options.auth.password=undefined] The password for auth
  321. * @param {string} [options.authMechanism=undefined] Mechanism for authentication: MDEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1
  322. * @param {object} [options.compression] Type of compression to use: snappy or zlib
  323. * @param {boolean} [options.fsync=false] Specify a file sync write concern
  324. * @param {array} [options.readPreferenceTags] Read preference tags
  325. * @param {number} [options.numberOfRetries=5] The number of retries for a tailable cursor
  326. * @param {boolean} [options.auto_reconnect=true] Enable auto reconnecting for single server instances
  327. * @param {number} [options.minSize] If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections
  328. * @param {MongoClient~connectCallback} [callback] The command result callback
  329. * @return {Promise<MongoClient>} returns Promise if no callback passed
  330. */
  331. MongoClient.connect = function(url, options, callback) {
  332. const args = Array.prototype.slice.call(arguments, 1);
  333. callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
  334. options = args.length ? args.shift() : null;
  335. options = options || {};
  336. // Create client
  337. const mongoClient = new MongoClient(url, options);
  338. // Execute the connect method
  339. return mongoClient.connect(callback);
  340. };
  341. /**
  342. * Starts a new session on the server
  343. *
  344. * @param {SessionOptions} [options] optional settings for a driver session
  345. * @return {ClientSession} the newly established session
  346. */
  347. MongoClient.prototype.startSession = function(options) {
  348. options = Object.assign({ explicit: true }, options);
  349. if (!this.topology) {
  350. throw new MongoError('Must connect to a server before calling this method');
  351. }
  352. if (!this.topology.hasSessionSupport()) {
  353. throw new MongoError('Current topology does not support sessions');
  354. }
  355. return this.topology.startSession(options, this.s.options);
  356. };
  357. /**
  358. * Runs a given operation with an implicitly created session. The lifetime of the session
  359. * will be handled without the need for user interaction.
  360. *
  361. * NOTE: presently the operation MUST return a Promise (either explicit or implicity as an async function)
  362. *
  363. * @param {Object} [options] Optional settings to be appled to implicitly created session
  364. * @param {Function} operation An operation to execute with an implicitly created session. The signature of this MUST be `(session) => {}`
  365. * @return {Promise}
  366. */
  367. MongoClient.prototype.withSession = function(options, operation) {
  368. if (typeof options === 'function') (operation = options), (options = undefined);
  369. const session = this.startSession(options);
  370. let cleanupHandler = (err, result, opts) => {
  371. // prevent multiple calls to cleanupHandler
  372. cleanupHandler = () => {
  373. throw new ReferenceError('cleanupHandler was called too many times');
  374. };
  375. opts = Object.assign({ throw: true }, opts);
  376. session.endSession();
  377. if (err) {
  378. if (opts.throw) throw err;
  379. return Promise.reject(err);
  380. }
  381. };
  382. try {
  383. const result = operation(session);
  384. return Promise.resolve(result)
  385. .then(result => cleanupHandler(null, result))
  386. .catch(err => cleanupHandler(err, null, { throw: true }));
  387. } catch (err) {
  388. return cleanupHandler(err, null, { throw: false });
  389. }
  390. };
  391. /**
  392. * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this cluster. Will ignore all changes to system collections, as well as the local, admin,
  393. * and config databases.
  394. * @method
  395. * @since 3.1.0
  396. * @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.
  397. * @param {object} [options] Optional settings
  398. * @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.
  399. * @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.
  400. * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query
  401. * @param {number} [options.batchSize] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.
  402. * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.
  403. * @param {ReadPreference} [options.readPreference] The read preference. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}.
  404. * @param {Timestamp} [options.startAtClusterTime] receive change events that occur after the specified timestamp
  405. * @param {ClientSession} [options.session] optional session to use for this operation
  406. * @return {ChangeStream} a ChangeStream instance.
  407. */
  408. MongoClient.prototype.watch = function(pipeline, options) {
  409. pipeline = pipeline || [];
  410. options = options || {};
  411. // Allow optionally not specifying a pipeline
  412. if (!Array.isArray(pipeline)) {
  413. options = pipeline;
  414. pipeline = [];
  415. }
  416. return new ChangeStream(this, pipeline, options);
  417. };
  418. /**
  419. * Return the mongo client logger
  420. * @method
  421. * @return {Logger} return the mongo client logger
  422. * @ignore
  423. */
  424. MongoClient.prototype.getLogger = function() {
  425. return this.s.options.logger;
  426. };
  427. module.exports = MongoClient;