mongo_client.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. 'use strict';
  2. const ChangeStream = require('./change_stream');
  3. const Db = require('./db');
  4. const EventEmitter = require('events').EventEmitter;
  5. const inherits = require('util').inherits;
  6. const MongoError = require('./core').MongoError;
  7. const deprecate = require('util').deprecate;
  8. const WriteConcern = require('./write_concern');
  9. const MongoDBNamespace = require('./utils').MongoDBNamespace;
  10. const ReadPreference = require('./core/topologies/read_preference');
  11. const maybePromise = require('./utils').maybePromise;
  12. const NativeTopology = require('./topologies/native_topology');
  13. const connect = require('./operations/connect').connect;
  14. const validOptions = require('./operations/connect').validOptions;
  15. /**
  16. * @fileOverview The **MongoClient** class is a class that allows for making Connections to MongoDB.
  17. *
  18. * @example
  19. * // Connect using a MongoClient instance
  20. * const MongoClient = require('mongodb').MongoClient;
  21. * const test = require('assert');
  22. * // Connection url
  23. * const url = 'mongodb://localhost:27017';
  24. * // Database Name
  25. * const dbName = 'test';
  26. * // Connect using MongoClient
  27. * const mongoClient = new MongoClient(url);
  28. * mongoClient.connect(function(err, client) {
  29. * const db = client.db(dbName);
  30. * client.close();
  31. * });
  32. *
  33. * @example
  34. * // Connect using the MongoClient.connect static method
  35. * const MongoClient = require('mongodb').MongoClient;
  36. * const test = require('assert');
  37. * // Connection url
  38. * const url = 'mongodb://localhost:27017';
  39. * // Database Name
  40. * const dbName = 'test';
  41. * // Connect using MongoClient
  42. * MongoClient.connect(url, function(err, client) {
  43. * const db = client.db(dbName);
  44. * client.close();
  45. * });
  46. */
  47. /**
  48. * A string specifying the level of a ReadConcern
  49. * @typedef {'local'|'available'|'majority'|'linearizable'|'snapshot'} ReadConcernLevel
  50. * @see https://docs.mongodb.com/manual/reference/read-concern/index.html#read-concern-levels
  51. */
  52. /**
  53. * Configuration options for drivers wrapping the node driver.
  54. *
  55. * @typedef {Object} DriverInfoOptions
  56. * @property {string} [name] The name of the driver
  57. * @property {string} [version] The version of the driver
  58. * @property {string} [platform] Optional platform information
  59. */
  60. /**
  61. * Configuration options for drivers wrapping the node driver.
  62. *
  63. * @typedef {Object} DriverInfoOptions
  64. * @property {string} [name] The name of the driver
  65. * @property {string} [version] The version of the driver
  66. * @property {string} [platform] Optional platform information
  67. */
  68. /**
  69. * @public
  70. * @typedef AutoEncryptionOptions
  71. * @property {MongoClient} [keyVaultClient] A `MongoClient` used to fetch keys from a key vault
  72. * @property {string} [keyVaultNamespace] The namespace where keys are stored in the key vault
  73. * @property {object} [kmsProviders] Configuration options that are used by specific KMS providers during key generation, encryption, and decryption.
  74. * @property {object} [schemaMap] A map of namespaces to a local JSON schema for encryption
  75. *
  76. * > **NOTE**: Supplying options.schemaMap provides more security than relying on JSON Schemas obtained from the server.
  77. * > It protects against a malicious server advertising a false JSON Schema, which could trick the client into sending decrypted data that should be encrypted.
  78. * > Schemas supplied in the schemaMap only apply to configuring automatic encryption for client side encryption.
  79. * > Other validation rules in the JSON schema will not be enforced by the driver and will result in an error.
  80. *
  81. * @property {object} [options] An optional hook to catch logging messages from the underlying encryption engine
  82. * @property {object} [extraOptions]
  83. * @property {boolean} [bypassAutoEncryption]
  84. */
  85. /**
  86. * @typedef {object} MongoClientOptions
  87. * @property {number} [poolSize] (**default**: 5) The maximum size of the individual server pool
  88. * @property {boolean} [ssl] (**default**: false) Enable SSL connection. *deprecated* use `tls` variants
  89. * @property {boolean} [sslValidate] (**default**: false) Validate mongod server certificate against Certificate Authority
  90. * @property {buffer} [sslCA] (**default**: undefined) SSL Certificate store binary buffer *deprecated* use `tls` variants
  91. * @property {buffer} [sslCert] (**default**: undefined) SSL Certificate binary buffer *deprecated* use `tls` variants
  92. * @property {buffer} [sslKey] (**default**: undefined) SSL Key file binary buffer *deprecated* use `tls` variants
  93. * @property {string} [sslPass] (**default**: undefined) SSL Certificate pass phrase *deprecated* use `tls` variants
  94. * @property {buffer} [sslCRL] (**default**: undefined) SSL Certificate revocation list binary buffer *deprecated* use `tls` variants
  95. * @property {boolean|function} [checkServerIdentity] (**default**: 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. *deprecated* use `tls` variants
  96. * @property {boolean} [tls] (**default**: false) Enable TLS connections
  97. * @property {boolean} [tlsInsecure] (**default**: false) Relax TLS constraints, disabling validation
  98. * @property {string} [tlsCAFile] A path to file with either a single or bundle of certificate authorities to be considered trusted when making a TLS connection
  99. * @property {string} [tlsCertificateKeyFile] A path to the client certificate file or the client private key file; in the case that they both are needed, the files should be concatenated
  100. * @property {string} [tlsCertificateKeyFilePassword] The password to decrypt the client private key to be used for TLS connections
  101. * @property {boolean} [tlsAllowInvalidCertificates] Specifies whether or not the driver should error when the server’s TLS certificate is invalid
  102. * @property {boolean} [tlsAllowInvalidHostnames] Specifies whether or not the driver should error when there is a mismatch between the server’s hostname and the hostname specified by the TLS certificate
  103. * @property {boolean} [autoReconnect] (**default**: true) Enable autoReconnect for single server instances
  104. * @property {boolean} [noDelay] (**default**: true) TCP Connection no delay
  105. * @property {boolean} [keepAlive] (**default**: true) TCP Connection keep alive enabled
  106. * @property {number} [keepAliveInitialDelay] (**default**: 120000) The number of milliseconds to wait before initiating keepAlive on the TCP socket
  107. * @property {number} [connectTimeoutMS] (**default**: 10000) How long to wait for a connection to be established before timing out
  108. * @property {number} [socketTimeoutMS] (**default**: 0) How long a send or receive on a socket can take before timing out
  109. * @property {number} [family] Version of IP stack. Can be 4, 6 or null (default). If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure
  110. * @property {number} [reconnectTries] (**default**: 30) Server attempt to reconnect #times
  111. * @property {number} [reconnectInterval] (**default**: 1000) Server will wait # milliseconds between retries
  112. * @property {boolean} [ha] (**default**: true) Control if high availability monitoring runs for Replicaset or Mongos proxies
  113. * @property {number} [haInterval] (**default**: 10000) The High availability period for replicaset inquiry
  114. * @property {string} [replicaSet] (**default**: undefined) The Replicaset set name
  115. * @property {number} [secondaryAcceptableLatencyMS] (**default**: 15) Cutoff latency point in MS for Replicaset member selection
  116. * @property {number} [acceptableLatencyMS] (**default**: 15) Cutoff latency point in MS for Mongos proxies selection
  117. * @property {boolean} [connectWithNoPrimary] (**default**: false) Sets if the driver should connect even if no primary is available
  118. * @property {string} [authSource] (**default**: undefined) Define the database to authenticate against
  119. * @property {(number|string)} [w] **Deprecated** The write concern. Use writeConcern instead.
  120. * @property {number} [wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead.
  121. * @property {boolean} [j] (**default**: false) **Deprecated** Specify a journal write concern. Use writeConcern instead.
  122. * @property {boolean} [fsync] (**default**: false) **Deprecated** Specify a file sync write concern. Use writeConcern instead.
  123. * @property {object|WriteConcern} [writeConcern] Specify write concern settings.
  124. * @property {boolean} [forceServerObjectId] (**default**: false) Force server to assign _id values instead of driver
  125. * @property {boolean} [serializeFunctions] (**default**: false) Serialize functions on any object
  126. * @property {Boolean} [ignoreUndefined] (**default**: false) Specify if the BSON serializer should ignore undefined fields
  127. * @property {boolean} [raw] (**default**: false) Return document results as raw BSON buffers
  128. * @property {number} [bufferMaxEntries] (**default**: -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
  129. * @property {(ReadPreference|string)} [readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST)
  130. * @property {object} [pkFactory] A primary key factory object for generation of custom _id keys
  131. * @property {object} [promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible
  132. * @property {object} [readConcern] Specify a read concern for the collection (only MongoDB 3.2 or higher supported)
  133. * @property {ReadConcernLevel} [readConcern.level] (**default**: {Level: 'local'}) Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported)
  134. * @property {number} [maxStalenessSeconds] (**default**: undefined) The max staleness to secondary reads (values under 10 seconds cannot be guaranteed)
  135. * @property {string} [loggerLevel] (**default**: undefined) The logging level (error/warn/info/debug)
  136. * @property {object} [logger] (**default**: undefined) Custom logger object
  137. * @property {boolean} [promoteValues] (**default**: true) Promotes BSON values to native types where possible, set to false to only receive wrapper types
  138. * @property {boolean} [promoteBuffers] (**default**: false) Promotes Binary BSON values to native Node Buffers
  139. * @property {boolean} [promoteLongs] (**default**: true) Promotes long values to number if they fit inside the 53 bits resolution
  140. * @property {boolean} [domainsEnabled] (**default**: false) Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit
  141. * @property {object} [validateOptions] (**default**: false) Validate MongoClient passed in options for correctness
  142. * @property {string} [appname] (**default**: 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
  143. * @property {string} [options.auth.user] (**default**: undefined) The username for auth
  144. * @property {string} [options.auth.password] (**default**: undefined) The password for auth
  145. * @property {string} [authMechanism] An authentication mechanism to use for connection authentication, see the {@link https://docs.mongodb.com/manual/reference/connection-string/#urioption.authMechanism|authMechanism} reference for supported options.
  146. * @property {object} [compression] Type of compression to use: snappy or zlib
  147. * @property {array} [readPreferenceTags] Read preference tags
  148. * @property {number} [numberOfRetries] (**default**: 5) The number of retries for a tailable cursor
  149. * @property {boolean} [auto_reconnect] (**default**: true) Enable auto reconnecting for single server instances
  150. * @property {boolean} [monitorCommands] (**default**: false) Enable command monitoring for this client
  151. * @property {number} [minSize] If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections
  152. * @property {boolean} [useNewUrlParser] (**default**: true) 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. Defaults to true, and must be explicitly set to false to use the legacy url parser.
  153. * @property {boolean} [useUnifiedTopology] Enables the new unified topology layer
  154. * @property {number} [localThresholdMS] (**default**: 15) **Only applies to the unified topology** The size of the latency window for selecting among multiple suitable servers
  155. * @property {number} [serverSelectionTimeoutMS] (**default**: 30000) **Only applies to the unified topology** How long to block for server selection before throwing an error
  156. * @property {number} [heartbeatFrequencyMS] (**default**: 10000) **Only applies to the unified topology** The frequency with which topology updates are scheduled
  157. * @property {number} [maxPoolSize] (**default**: 10) **Only applies to the unified topology** The maximum number of connections that may be associated with a pool at a given time. This includes in use and available connections.
  158. * @property {number} [minPoolSize] (**default**: 0) **Only applies to the unified topology** The minimum number of connections that MUST exist at any moment in a single connection pool.
  159. * @property {number} [maxIdleTimeMS] **Only applies to the unified topology** The maximum amount of time a connection should remain idle in the connection pool before being marked idle. The default is infinity.
  160. * @property {number} [waitQueueTimeoutMS] (**default**: 0) **Only applies to the unified topology** The maximum amount of time operation execution should wait for a connection to become available. The default is 0 which means there is no limit.
  161. * @property {AutoEncryptionOptions} [autoEncryption] Optionally enable client side auto encryption.
  162. *
  163. * > Automatic encryption is an enterprise only feature that only applies to operations on a collection. Automatic encryption is not supported for operations on a database or view, and operations that are not bypassed will result in error
  164. * > (see [libmongocrypt: Auto Encryption Allow-List](https://github.com/mongodb/specifications/blob/master/source/client-side-encryption/client-side-encryption.rst#libmongocrypt-auto-encryption-allow-list)). To bypass automatic encryption for all operations, set bypassAutoEncryption=true in AutoEncryptionOpts.
  165. * >
  166. * > Automatic encryption requires the authenticated user to have the [listCollections privilege action](https://docs.mongodb.com/manual/reference/command/listCollections/#dbcmd.listCollections).
  167. * >
  168. * > If a MongoClient with a limited connection pool size (i.e a non-zero maxPoolSize) is configured with AutoEncryptionOptions, a separate internal MongoClient is created if any of the following are true:
  169. * > - AutoEncryptionOptions.keyVaultClient is not passed.
  170. * > - AutoEncryptionOptions.bypassAutomaticEncryption is false.
  171. * > If an internal MongoClient is created, it is configured with the same options as the parent MongoClient except minPoolSize is set to 0 and AutoEncryptionOptions is omitted.
  172. *
  173. * @property {DriverInfoOptions} [driverInfo] Allows a wrapping driver to amend the client metadata generated by the driver to include information about the wrapping driver
  174. * @property {boolean} [directConnection] (**default**: false) Enable directConnection
  175. * @property {function} [callback] The command result callback
  176. */
  177. /**
  178. * Creates a new MongoClient instance
  179. * @constructor
  180. * @extends {EventEmitter}
  181. * @param {string} url The connection URI string
  182. * @param {MongoClientOptions} [options] Optional settings
  183. */
  184. function MongoClient(url, options) {
  185. if (!(this instanceof MongoClient)) return new MongoClient(url, options);
  186. // Set up event emitter
  187. EventEmitter.call(this);
  188. if (options && options.autoEncryption) require('./encrypter'); // Does CSFLE lib check
  189. // The internal state
  190. this.s = {
  191. url: url,
  192. options: options || {},
  193. promiseLibrary: (options && options.promiseLibrary) || Promise,
  194. dbCache: new Map(),
  195. sessions: new Set(),
  196. writeConcern: WriteConcern.fromOptions(options),
  197. readPreference: ReadPreference.fromOptions(options) || ReadPreference.primary,
  198. namespace: new MongoDBNamespace('admin')
  199. };
  200. }
  201. /**
  202. * @ignore
  203. */
  204. inherits(MongoClient, EventEmitter);
  205. Object.defineProperty(MongoClient.prototype, 'writeConcern', {
  206. enumerable: true,
  207. get: function() {
  208. return this.s.writeConcern;
  209. }
  210. });
  211. Object.defineProperty(MongoClient.prototype, 'readPreference', {
  212. enumerable: true,
  213. get: function() {
  214. return this.s.readPreference;
  215. }
  216. });
  217. /**
  218. * The callback format for results
  219. * @callback MongoClient~connectCallback
  220. * @param {MongoError} error An error instance representing the error during the execution.
  221. * @param {MongoClient} client The connected client.
  222. */
  223. /**
  224. * Connect to MongoDB using a url as documented at
  225. *
  226. * docs.mongodb.org/manual/reference/connection-string/
  227. *
  228. * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver
  229. *
  230. * @method
  231. * @param {MongoClient~connectCallback} [callback] The command result callback
  232. * @return {Promise<MongoClient>} returns Promise if no callback passed
  233. */
  234. MongoClient.prototype.connect = function(callback) {
  235. if (typeof callback === 'string') {
  236. throw new TypeError('`connect` only accepts a callback');
  237. }
  238. const client = this;
  239. return maybePromise(this, callback, cb => {
  240. const err = validOptions(client.s.options);
  241. if (err) return cb(err);
  242. connect(client, client.s.url, client.s.options, err => {
  243. if (err) return cb(err);
  244. cb(null, client);
  245. });
  246. });
  247. };
  248. MongoClient.prototype.logout = deprecate(function(options, callback) {
  249. if (typeof options === 'function') (callback = options), (options = {});
  250. if (typeof callback === 'function') callback(null, true);
  251. }, 'Multiple authentication is prohibited on a connected client, please only authenticate once per MongoClient');
  252. /**
  253. * Close the db and its underlying connections
  254. * @method
  255. * @param {boolean} [force=false] Force close, emitting no events
  256. * @param {Db~noResultCallback} [callback] The result callback
  257. * @return {Promise} returns Promise if no callback passed
  258. */
  259. MongoClient.prototype.close = function(force, callback) {
  260. if (typeof force === 'function') {
  261. callback = force;
  262. force = false;
  263. }
  264. const client = this;
  265. return maybePromise(this, callback, cb => {
  266. const completeClose = err => {
  267. client.emit('close', client);
  268. if (!(client.topology instanceof NativeTopology)) {
  269. for (const item of client.s.dbCache) {
  270. item[1].emit('close', client);
  271. }
  272. }
  273. client.removeAllListeners('close');
  274. cb(err);
  275. };
  276. if (client.topology == null) {
  277. completeClose();
  278. return;
  279. }
  280. client.topology.close(force, err => {
  281. const encrypter = client.topology.s.options.encrypter;
  282. if (encrypter) {
  283. return encrypter.close(client, force, err2 => {
  284. completeClose(err || err2);
  285. });
  286. }
  287. completeClose(err);
  288. });
  289. });
  290. };
  291. /**
  292. * Create a new Db instance sharing the current socket connections. Be aware that the new db instances are
  293. * related in a parent-child relationship to the original instance so that events are correctly emitted on child
  294. * db instances. Child db instances are cached so performing db('db1') twice will return the same instance.
  295. * You can control these behaviors with the options noListener and returnNonCachedInstance.
  296. *
  297. * @method
  298. * @param {string} [dbName] The name of the database we want to use. If not provided, use database name from connection string.
  299. * @param {object} [options] Optional settings.
  300. * @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection.
  301. * @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created
  302. * @return {Db}
  303. */
  304. MongoClient.prototype.db = function(dbName, options) {
  305. options = options || {};
  306. // Default to db from connection string if not provided
  307. if (!dbName) {
  308. dbName = this.s.options.dbName;
  309. }
  310. // Copy the options and add out internal override of the not shared flag
  311. const finalOptions = Object.assign({}, this.s.options, options);
  312. // Do we have the db in the cache already
  313. if (this.s.dbCache.has(dbName) && finalOptions.returnNonCachedInstance !== true) {
  314. return this.s.dbCache.get(dbName);
  315. }
  316. // Add promiseLibrary
  317. finalOptions.promiseLibrary = this.s.promiseLibrary;
  318. // If no topology throw an error message
  319. if (!this.topology) {
  320. throw new MongoError('MongoClient must be connected before calling MongoClient.prototype.db');
  321. }
  322. // Return the db object
  323. const db = new Db(dbName, this.topology, finalOptions);
  324. // Add the db to the cache
  325. this.s.dbCache.set(dbName, db);
  326. // Return the database
  327. return db;
  328. };
  329. /**
  330. * Check if MongoClient is connected
  331. *
  332. * @method
  333. * @param {object} [options] Optional settings.
  334. * @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection.
  335. * @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created
  336. * @return {boolean}
  337. */
  338. MongoClient.prototype.isConnected = function(options) {
  339. options = options || {};
  340. if (!this.topology) return false;
  341. return this.topology.isConnected(options);
  342. };
  343. /**
  344. * Connect to MongoDB using a url as documented at
  345. *
  346. * docs.mongodb.org/manual/reference/connection-string/
  347. *
  348. * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver
  349. *
  350. * @method
  351. * @static
  352. * @param {string} url The connection URI string
  353. * @param {MongoClientOptions} [options] Optional settings
  354. * @return {Promise<MongoClient>} returns Promise if no callback passed
  355. */
  356. MongoClient.connect = function(url, options, callback) {
  357. const args = Array.prototype.slice.call(arguments, 1);
  358. callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
  359. options = args.length ? args.shift() : null;
  360. options = options || {};
  361. // Create client
  362. const mongoClient = new MongoClient(url, options);
  363. // Execute the connect method
  364. return mongoClient.connect(callback);
  365. };
  366. /**
  367. * Starts a new session on the server
  368. *
  369. * @param {SessionOptions} [options] optional settings for a driver session
  370. * @return {ClientSession} the newly established session
  371. */
  372. MongoClient.prototype.startSession = function(options) {
  373. options = Object.assign({ explicit: true }, options);
  374. if (!this.topology) {
  375. throw new MongoError('Must connect to a server before calling this method');
  376. }
  377. return this.topology.startSession(options, this.s.options);
  378. };
  379. /**
  380. * Runs a given operation with an implicitly created session. The lifetime of the session
  381. * will be handled without the need for user interaction.
  382. *
  383. * NOTE: presently the operation MUST return a Promise (either explicit or implicity as an async function)
  384. *
  385. * @param {Object} [options] Optional settings to be appled to implicitly created session
  386. * @param {Function} operation An operation to execute with an implicitly created session. The signature of this MUST be `(session) => {}`
  387. * @return {Promise}
  388. */
  389. MongoClient.prototype.withSession = function(options, operation) {
  390. if (typeof options === 'function') (operation = options), (options = undefined);
  391. const session = this.startSession(options);
  392. let cleanupHandler = (err, result, opts) => {
  393. // prevent multiple calls to cleanupHandler
  394. cleanupHandler = () => {
  395. throw new ReferenceError('cleanupHandler was called too many times');
  396. };
  397. opts = Object.assign({ throw: true }, opts);
  398. session.endSession();
  399. if (err) {
  400. if (opts.throw) throw err;
  401. return Promise.reject(err);
  402. }
  403. };
  404. try {
  405. const result = operation(session);
  406. return Promise.resolve(result)
  407. .then(result => cleanupHandler(null, result))
  408. .catch(err => cleanupHandler(err, null, { throw: true }));
  409. } catch (err) {
  410. return cleanupHandler(err, null, { throw: false });
  411. }
  412. };
  413. /**
  414. * 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,
  415. * and config databases.
  416. * @method
  417. * @since 3.1.0
  418. * @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.
  419. * @param {object} [options] Optional settings
  420. * @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.
  421. * @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.
  422. * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query
  423. * @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}.
  424. * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.
  425. * @param {ReadPreference} [options.readPreference] The read preference. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}.
  426. * @param {Timestamp} [options.startAtOperationTime] receive change events that occur after the specified timestamp
  427. * @param {ClientSession} [options.session] optional session to use for this operation
  428. * @return {ChangeStream} a ChangeStream instance.
  429. */
  430. MongoClient.prototype.watch = function(pipeline, options) {
  431. pipeline = pipeline || [];
  432. options = options || {};
  433. // Allow optionally not specifying a pipeline
  434. if (!Array.isArray(pipeline)) {
  435. options = pipeline;
  436. pipeline = [];
  437. }
  438. return new ChangeStream(this, pipeline, options);
  439. };
  440. /**
  441. * Return the mongo client logger
  442. * @method
  443. * @return {Logger} return the mongo client logger
  444. * @ignore
  445. */
  446. MongoClient.prototype.getLogger = function() {
  447. return this.s.options.logger;
  448. };
  449. module.exports = MongoClient;