mongo_client.js 24 KB

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