mongo_client.js 28 KB

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