mongodb 3.6.6 → 3.6.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/HISTORY.md CHANGED
@@ -2,6 +2,19 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
4
4
 
5
+ ### [3.6.7](https://github.com/mongodb/node-mongodb-native/compare/v3.6.6...v3.6.7) (2021-05-18)
6
+
7
+
8
+ ### Bug Fixes
9
+
10
+ * **docs:** removing incorrect apm docs ([#2793](https://github.com/mongodb/node-mongodb-native/issues/2793)) ([971259a](https://github.com/mongodb/node-mongodb-native/commit/971259a868a8018e90ebc2f28d151eb7af3dd50a))
11
+ * **NODE-3173:** Preserve sort key order for numeric string keys ([#2790](https://github.com/mongodb/node-mongodb-native/issues/2790)) ([730f43a](https://github.com/mongodb/node-mongodb-native/commit/730f43af6d9e53603af998353b720d8161426d8c))
12
+ * **NODE-3176:** handle errors from MessageStream ([#2774](https://github.com/mongodb/node-mongodb-native/issues/2774)) ([f1afcc4](https://github.com/mongodb/node-mongodb-native/commit/f1afcc4efbc41ce436812a6bfa22843e939ab5cf))
13
+ * **NODE-3192:** check clusterTime is defined before access ([#2806](https://github.com/mongodb/node-mongodb-native/issues/2806)) ([6ceace6](https://github.com/mongodb/node-mongodb-native/commit/6ceace6b245c42b8498fb1b13e7c37a97a46946d))
14
+ * **NODE-3252:** state transistion from DISCONNECTED ([#2807](https://github.com/mongodb/node-mongodb-native/issues/2807)) ([5d8f649](https://github.com/mongodb/node-mongodb-native/commit/5d8f6493a0ba4b525434c0868e2ae12315b4c249))
15
+ * **sdam:** topology no longer causes close event ([#2791](https://github.com/mongodb/node-mongodb-native/issues/2791)) ([16e7064](https://github.com/mongodb/node-mongodb-native/commit/16e70642f25954a03b91a2c2991cea96b8356de7))
16
+ * invalid case on writeconcern makes skip check fail ([#2773](https://github.com/mongodb/node-mongodb-native/issues/2773)) ([b1363c2](https://github.com/mongodb/node-mongodb-native/commit/b1363c26db5da5003f9db43be7e8d6e9007d45bd))
17
+
5
18
  ### [3.6.6](https://github.com/mongodb/node-mongodb-native/compare/v3.6.5...v3.6.6) (2021-04-06)
6
19
 
7
20
 
@@ -5,6 +5,7 @@ const MongoError = require('../core').MongoError;
5
5
  const ObjectID = require('../core').BSON.ObjectID;
6
6
  const BSON = require('../core').BSON;
7
7
  const MongoWriteConcernError = require('../core').MongoWriteConcernError;
8
+ const emitWarningOnce = require('../utils').emitWarningOnce;
8
9
  const toError = require('../utils').toError;
9
10
  const handleCallback = require('../utils').handleCallback;
10
11
  const applyRetryableWrites = require('../utils').applyRetryableWrites;
@@ -70,6 +71,45 @@ class BulkWriteResult {
70
71
  this.result = bulkResult;
71
72
  }
72
73
 
74
+ /** Number of documents inserted. */
75
+ get insertedCount() {
76
+ return typeof this.result.nInserted !== 'number' ? 0 : this.result.nInserted;
77
+ }
78
+ /** Number of documents matched for update. */
79
+ get matchedCount() {
80
+ return typeof this.result.nMatched !== 'number' ? 0 : this.result.nMatched;
81
+ }
82
+ /** Number of documents modified. */
83
+ get modifiedCount() {
84
+ return typeof this.result.nModified !== 'number' ? 0 : this.result.nModified;
85
+ }
86
+ /** Number of documents deleted. */
87
+ get deletedCount() {
88
+ return typeof this.result.nRemoved !== 'number' ? 0 : this.result.nRemoved;
89
+ }
90
+ /** Number of documents upserted. */
91
+ get upsertedCount() {
92
+ return !this.result.upserted ? 0 : this.result.upserted.length;
93
+ }
94
+
95
+ /** Upserted document generated Id's, hash key is the index of the originating operation */
96
+ get upsertedIds() {
97
+ const upserted = {};
98
+ for (const doc of !this.result.upserted ? [] : this.result.upserted) {
99
+ upserted[doc.index] = doc._id;
100
+ }
101
+ return upserted;
102
+ }
103
+
104
+ /** Inserted document generated Id's, hash key is the index of the originating operation */
105
+ get insertedIds() {
106
+ const inserted = {};
107
+ for (const doc of !this.result.insertedIds ? [] : this.result.insertedIds) {
108
+ inserted[doc.index] = doc._id;
109
+ }
110
+ return inserted;
111
+ }
112
+
73
113
  /**
74
114
  * Evaluates to true if the bulk operation correctly executes
75
115
  * @type {boolean}
@@ -571,6 +611,35 @@ class BulkWriteError extends MongoError {
571
611
  this.name = 'BulkWriteError';
572
612
  this.result = result;
573
613
  }
614
+
615
+ /** Number of documents inserted. */
616
+ get insertedCount() {
617
+ return this.result.insertedCount;
618
+ }
619
+ /** Number of documents matched for update. */
620
+ get matchedCount() {
621
+ return this.result.matchedCount;
622
+ }
623
+ /** Number of documents modified. */
624
+ get modifiedCount() {
625
+ return this.result.modifiedCount;
626
+ }
627
+ /** Number of documents deleted. */
628
+ get deletedCount() {
629
+ return this.result.deletedCount;
630
+ }
631
+ /** Number of documents upserted. */
632
+ get upsertedCount() {
633
+ return this.result.upsertedCount;
634
+ }
635
+ /** Inserted document generated Id's, hash key is the index of the originating operation */
636
+ get insertedIds() {
637
+ return this.result.insertedIds;
638
+ }
639
+ /** Upserted document generated Id's, hash key is the index of the originating operation */
640
+ get upsertedIds() {
641
+ return this.result.upsertedIds;
642
+ }
574
643
  }
575
644
 
576
645
  /**
@@ -737,15 +806,19 @@ class FindOperators {
737
806
 
738
807
  /**
739
808
  * backwards compatability for deleteOne
809
+ * @deprecated
740
810
  */
741
811
  removeOne() {
812
+ emitWarningOnce('bulk operation `removeOne` has been deprecated, please use `deleteOne`');
742
813
  return this.deleteOne();
743
814
  }
744
815
 
745
816
  /**
746
817
  * backwards compatability for delete
818
+ * @deprecated
747
819
  */
748
820
  remove() {
821
+ emitWarningOnce('bulk operation `remove` has been deprecated, please use `delete`');
749
822
  return this.delete();
750
823
  }
751
824
  }
@@ -1041,6 +1114,9 @@ class BulkOperationBase {
1041
1114
  }
1042
1115
 
1043
1116
  if (op.insertMany) {
1117
+ emitWarningOnce(
1118
+ 'bulk operation `insertMany` has been deprecated; use multiple `insertOne` ops instead'
1119
+ );
1044
1120
  for (let i = 0; i < op.insertMany.length; i++) {
1045
1121
  if (forceServerObjectId !== true && op.insertMany[i]._id == null)
1046
1122
  op.insertMany[i]._id = new ObjectID();
@@ -58,38 +58,9 @@ class Connection extends EventEmitter {
58
58
  /* ignore errors, listen to `close` instead */
59
59
  });
60
60
 
61
- stream.on('close', () => {
62
- if (this.closed) {
63
- return;
64
- }
65
-
66
- this.closed = true;
67
- this[kQueue].forEach(op =>
68
- op.cb(new MongoNetworkError(`connection ${this.id} to ${this.address} closed`))
69
- );
70
- this[kQueue].clear();
71
-
72
- this.emit('close');
73
- });
74
-
75
- stream.on('timeout', () => {
76
- if (this.closed) {
77
- return;
78
- }
79
-
80
- stream.destroy();
81
- this.closed = true;
82
- this[kQueue].forEach(op =>
83
- op.cb(
84
- new MongoNetworkTimeoutError(`connection ${this.id} to ${this.address} timed out`, {
85
- beforeHandshake: this[kIsMaster] == null
86
- })
87
- )
88
- );
89
-
90
- this[kQueue].clear();
91
- this.emit('close');
92
- });
61
+ this[kMessageStream].on('error', error => this.handleIssue({ destroy: error }));
62
+ stream.on('close', () => this.handleIssue({ isClose: true }));
63
+ stream.on('timeout', () => this.handleIssue({ isTimeout: true, destroy: true }));
93
64
 
94
65
  // hook the message stream up to the passed in stream
95
66
  stream.pipe(this[kMessageStream]);
@@ -132,6 +103,39 @@ class Connection extends EventEmitter {
132
103
  this[kLastUseTime] = now();
133
104
  }
134
105
 
106
+ /**
107
+ * @param {{ isTimeout?: boolean; isClose?: boolean; destroy?: boolean | Error }} issue
108
+ */
109
+ handleIssue(issue) {
110
+ if (this.closed) {
111
+ return;
112
+ }
113
+
114
+ if (issue.destroy) {
115
+ this[kStream].destroy(typeof issue.destroy === 'boolean' ? undefined : issue.destroy);
116
+ }
117
+
118
+ this.closed = true;
119
+
120
+ for (const idAndOp of this[kQueue]) {
121
+ const op = idAndOp[1];
122
+ if (issue.isTimeout) {
123
+ op.cb(
124
+ new MongoNetworkTimeoutError(`connection ${this.id} to ${this.address} timed out`, {
125
+ beforeHandshake: !!this[kIsMaster]
126
+ })
127
+ );
128
+ } else if (issue.isClose) {
129
+ op.cb(new MongoNetworkError(`connection ${this.id} to ${this.address} closed`));
130
+ } else {
131
+ op.cb(typeof issue.destroy === 'boolean' ? undefined : issue.destroy);
132
+ }
133
+ }
134
+
135
+ this[kQueue].clear();
136
+ this.emit('close');
137
+ }
138
+
135
139
  destroy(options, callback) {
136
140
  if (typeof options === 'function') {
137
141
  callback = options;
package/lib/collection.js CHANGED
@@ -1655,7 +1655,7 @@ Collection.prototype.stats = function(options, callback) {
1655
1655
 
1656
1656
  /**
1657
1657
  * @typedef {Object} Collection~findAndModifyWriteOpResult
1658
- * @property {object} value Document returned from the `findAndModify` command. If no documents were found, `value` will be `null` by default (`returnOriginal: true`), even if a document was upserted; if `returnOriginal` was false, the upserted document will be returned in that case.
1658
+ * @property {object} value Document returned from the `findAndModify` command. If no documents were found, `value` will be `null` by default even if a document was upserted unless `returnDocument` is specified as `'after'`, in which case the upserted document will be returned.
1659
1659
  * @property {object} lastErrorObject The raw lastErrorObject returned from the command. See {@link https://docs.mongodb.com/manual/reference/command/findAndModify/index.html#lasterrorobject|findAndModify command documentation}.
1660
1660
  * @property {Number} ok Is 1 if the command executed correctly.
1661
1661
  */
@@ -1716,7 +1716,8 @@ Collection.prototype.findOneAndDelete = function(filter, options, callback) {
1716
1716
  * @param {object} [options.projection] Limits the fields to return for all matching documents.
1717
1717
  * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents.
1718
1718
  * @param {boolean} [options.upsert=false] Upsert the document if it does not exist.
1719
- * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true.
1719
+ * @param {'before'|'after'} [options.returnDocument='before'] When set to `'after'`, returns the updated document rather than the original. The default is `'before'`.
1720
+ * @param {boolean} [options.returnOriginal=true] **Deprecated** Use `options.returnDocument` instead.
1720
1721
  * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value
1721
1722
  * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
1722
1723
  * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
@@ -1725,22 +1726,29 @@ Collection.prototype.findOneAndDelete = function(filter, options, callback) {
1725
1726
  * @param {Collection~findAndModifyCallback} [callback] The collection result callback
1726
1727
  * @return {Promise<Collection~findAndModifyWriteOpResultObject>} returns Promise if no callback passed
1727
1728
  */
1728
- Collection.prototype.findOneAndReplace = function(filter, replacement, options, callback) {
1729
- if (typeof options === 'function') (callback = options), (options = {});
1730
- options = options || {};
1729
+ Collection.prototype.findOneAndReplace = deprecateOptions(
1730
+ {
1731
+ name: 'collection.findOneAndReplace',
1732
+ deprecatedOptions: ['returnOriginal'],
1733
+ optionsIndex: 2
1734
+ },
1735
+ function(filter, replacement, options, callback) {
1736
+ if (typeof options === 'function') (callback = options), (options = {});
1737
+ options = options || {};
1731
1738
 
1732
- // Add ignoreUndefined
1733
- if (this.s.options.ignoreUndefined) {
1734
- options = Object.assign({}, options);
1735
- options.ignoreUndefined = this.s.options.ignoreUndefined;
1736
- }
1739
+ // Add ignoreUndefined
1740
+ if (this.s.options.ignoreUndefined) {
1741
+ options = Object.assign({}, options);
1742
+ options.ignoreUndefined = this.s.options.ignoreUndefined;
1743
+ }
1737
1744
 
1738
- return executeOperation(
1739
- this.s.topology,
1740
- new FindOneAndReplaceOperation(this, filter, replacement, options),
1741
- callback
1742
- );
1743
- };
1745
+ return executeOperation(
1746
+ this.s.topology,
1747
+ new FindOneAndReplaceOperation(this, filter, replacement, options),
1748
+ callback
1749
+ );
1750
+ }
1751
+ );
1744
1752
 
1745
1753
  /**
1746
1754
  * Find a document and update it in one atomic operation. Requires a write lock for the duration of the operation.
@@ -1757,7 +1765,8 @@ Collection.prototype.findOneAndReplace = function(filter, replacement, options,
1757
1765
  * @param {object} [options.projection] Limits the fields to return for all matching documents.
1758
1766
  * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents.
1759
1767
  * @param {boolean} [options.upsert=false] Upsert the document if it does not exist.
1760
- * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true.
1768
+ * @param {'before'|'after'} [options.returnDocument='before'] When set to `'after'`, returns the updated document rather than the original. The default is `'before'`.
1769
+ * @param {boolean} [options.returnOriginal=true] **Deprecated** Use `options.returnDocument` instead.
1761
1770
  * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value
1762
1771
  * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
1763
1772
  * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
@@ -1766,22 +1775,29 @@ Collection.prototype.findOneAndReplace = function(filter, replacement, options,
1766
1775
  * @param {Collection~findAndModifyCallback} [callback] The collection result callback
1767
1776
  * @return {Promise<Collection~findAndModifyWriteOpResultObject>} returns Promise if no callback passed
1768
1777
  */
1769
- Collection.prototype.findOneAndUpdate = function(filter, update, options, callback) {
1770
- if (typeof options === 'function') (callback = options), (options = {});
1771
- options = options || {};
1778
+ Collection.prototype.findOneAndUpdate = deprecateOptions(
1779
+ {
1780
+ name: 'collection.findOneAndUpdate',
1781
+ deprecatedOptions: ['returnOriginal'],
1782
+ optionsIndex: 2
1783
+ },
1784
+ function(filter, update, options, callback) {
1785
+ if (typeof options === 'function') (callback = options), (options = {});
1786
+ options = options || {};
1772
1787
 
1773
- // Add ignoreUndefined
1774
- if (this.s.options.ignoreUndefined) {
1775
- options = Object.assign({}, options);
1776
- options.ignoreUndefined = this.s.options.ignoreUndefined;
1777
- }
1788
+ // Add ignoreUndefined
1789
+ if (this.s.options.ignoreUndefined) {
1790
+ options = Object.assign({}, options);
1791
+ options.ignoreUndefined = this.s.options.ignoreUndefined;
1792
+ }
1778
1793
 
1779
- return executeOperation(
1780
- this.s.topology,
1781
- new FindOneAndUpdateOperation(this, filter, update, options),
1782
- callback
1783
- );
1784
- };
1794
+ return executeOperation(
1795
+ this.s.topology,
1796
+ new FindOneAndUpdateOperation(this, filter, update, options),
1797
+ callback
1798
+ );
1799
+ }
1800
+ );
1785
1801
 
1786
1802
  /**
1787
1803
  * Find and update a document.
@@ -2199,7 +2215,6 @@ Collection.prototype.initializeUnorderedBulkOp = function(options) {
2199
2215
  * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings.
2200
2216
  * @param {ClientSession} [options.session] optional session to use for this operation
2201
2217
  * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
2202
- * @param {OrderedBulkOperation} callback The command result callback
2203
2218
  * @return {null}
2204
2219
  */
2205
2220
  Collection.prototype.initializeOrderedBulkOp = function(options) {
@@ -49,16 +49,16 @@ class MongoCredentials {
49
49
  this.mechanism = options.mechanism || 'default';
50
50
  this.mechanismProperties = options.mechanismProperties || {};
51
51
 
52
- if (this.mechanism.match(/MONGODB-AWS/i)) {
53
- if (this.username == null && process.env.AWS_ACCESS_KEY_ID) {
52
+ if (/MONGODB-AWS/i.test(this.mechanism)) {
53
+ if (!this.username && process.env.AWS_ACCESS_KEY_ID) {
54
54
  this.username = process.env.AWS_ACCESS_KEY_ID;
55
55
  }
56
56
 
57
- if (this.password == null && process.env.AWS_SECRET_ACCESS_KEY) {
57
+ if (!this.password && process.env.AWS_SECRET_ACCESS_KEY) {
58
58
  this.password = process.env.AWS_SECRET_ACCESS_KEY;
59
59
  }
60
60
 
61
- if (this.mechanismProperties.AWS_SESSION_TOKEN == null && process.env.AWS_SESSION_TOKEN) {
61
+ if (!this.mechanismProperties.AWS_SESSION_TOKEN && process.env.AWS_SESSION_TOKEN) {
62
62
  this.mechanismProperties.AWS_SESSION_TOKEN = process.env.AWS_SESSION_TOKEN;
63
63
  }
64
64
  }
@@ -90,7 +90,7 @@ class MongoCredentials {
90
90
  */
91
91
  resolveAuthMechanism(ismaster) {
92
92
  // If the mechanism is not "default", then it does not need to be resolved
93
- if (this.mechanism.match(/DEFAULT/i)) {
93
+ if (/DEFAULT/i.test(this.mechanism)) {
94
94
  return new MongoCredentials({
95
95
  username: this.username,
96
96
  password: this.password,
@@ -359,7 +359,6 @@ class Topology extends EventEmitter {
359
359
  this.emit('topologyClosed', new events.TopologyClosedEvent(this.s.id));
360
360
 
361
361
  stateTransition(this, STATE_CLOSED);
362
- this.emit('close');
363
362
 
364
363
  if (typeof callback === 'function') {
365
364
  callback(err);
@@ -558,7 +558,7 @@ var monitorServer = function(host, self, options) {
558
558
  self.s.options.secondaryOnlyConnectionAllowed) ||
559
559
  self.s.replicaSetState.hasPrimary())
560
560
  ) {
561
- stateTransition(self, CONNECTED);
561
+ stateTransition(self, CONNECTING);
562
562
 
563
563
  // Rexecute any stalled operation
564
564
  rexecuteOperations(self);
@@ -45,14 +45,19 @@ function _command(server, ns, cmd, options, callback) {
45
45
  const shouldUseOpMsg = supportsOpMsg(server);
46
46
  const session = options.session;
47
47
 
48
- let clusterTime = server.clusterTime;
48
+ const serverClusterTime = server.clusterTime;
49
+ let clusterTime = serverClusterTime;
49
50
  let finalCmd = Object.assign({}, cmd);
50
51
  if (hasSessionSupport(server) && session) {
52
+ const sessionClusterTime = session.clusterTime;
51
53
  if (
52
- session.clusterTime &&
53
- session.clusterTime.clusterTime.greaterThan(clusterTime.clusterTime)
54
+ serverClusterTime &&
55
+ serverClusterTime.clusterTime &&
56
+ sessionClusterTime &&
57
+ sessionClusterTime.clusterTime &&
58
+ sessionClusterTime.clusterTime.greaterThan(serverClusterTime.clusterTime)
54
59
  ) {
55
- clusterTime = session.clusterTime;
60
+ clusterTime = sessionClusterTime;
56
61
  }
57
62
 
58
63
  const err = applySession(session, finalCmd, options);
@@ -61,8 +66,8 @@ function _command(server, ns, cmd, options, callback) {
61
66
  }
62
67
  }
63
68
 
64
- // if we have a known cluster time, gossip it
65
69
  if (clusterTime) {
70
+ // if we have a known cluster time, gossip it
66
71
  finalCmd.$clusterTime = clusterTime;
67
72
  }
68
73
 
@@ -90,86 +90,82 @@ const validOptions = require('./operations/connect').validOptions;
90
90
  */
91
91
 
92
92
  /**
93
- * Creates a new MongoClient instance
94
- * @class
95
- * @param {string} url The connection URI string
96
- * @param {object} [options] Optional settings
97
- * @param {number} [options.poolSize=5] The maximum size of the individual server pool
98
- * @param {boolean} [options.ssl=false] Enable SSL connection. *deprecated* use `tls` variants
99
- * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against Certificate Authority
100
- * @param {buffer} [options.sslCA=undefined] SSL Certificate store binary buffer *deprecated* use `tls` variants
101
- * @param {buffer} [options.sslCert=undefined] SSL Certificate binary buffer *deprecated* use `tls` variants
102
- * @param {buffer} [options.sslKey=undefined] SSL Key file binary buffer *deprecated* use `tls` variants
103
- * @param {string} [options.sslPass=undefined] SSL Certificate pass phrase *deprecated* use `tls` variants
104
- * @param {buffer} [options.sslCRL=undefined] SSL Certificate revocation list binary buffer *deprecated* use `tls` variants
105
- * @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. *deprecated* use `tls` variants
106
- * @param {boolean} [options.tls=false] Enable TLS connections
107
- * @param {boolean} [options.tlsInsecure=false] Relax TLS constraints, disabling validation
108
- * @param {string} [options.tlsCAFile] A path to file with either a single or bundle of certificate authorities to be considered trusted when making a TLS connection
109
- * @param {string} [options.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
110
- * @param {string} [options.tlsCertificateKeyFilePassword] The password to decrypt the client private key to be used for TLS connections
111
- * @param {boolean} [options.tlsAllowInvalidCertificates] Specifies whether or not the driver should error when the server’s TLS certificate is invalid
112
- * @param {boolean} [options.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
113
- * @param {boolean} [options.autoReconnect=true] Enable autoReconnect for single server instances
114
- * @param {boolean} [options.noDelay=true] TCP Connection no delay
115
- * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled
116
- * @param {number} [options.keepAliveInitialDelay=120000] The number of milliseconds to wait before initiating keepAlive on the TCP socket
117
- * @param {number} [options.connectTimeoutMS=10000] How long to wait for a connection to be established before timing out
118
- * @param {number} [options.socketTimeoutMS=0] How long a send or receive on a socket can take before timing out
119
- * @param {number} [options.family] Version of IP stack. Can be 4, 6 or null (default).
120
- * If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure
121
- * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times
122
- * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries
123
- * @param {boolean} [options.ha=true] Control if high availability monitoring runs for Replicaset or Mongos proxies
124
- * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry
125
- * @param {string} [options.replicaSet=undefined] The Replicaset set name
126
- * @param {number} [options.secondaryAcceptableLatencyMS=15] Cutoff latency point in MS for Replicaset member selection
127
- * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for Mongos proxies selection
128
- * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available
129
- * @param {string} [options.authSource=undefined] Define the database to authenticate against
130
- * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead.
131
- * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead.
132
- * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead.
133
- * @param {boolean} [options.fsync=false] **Deprecated** Specify a file sync write concern. Use writeConcern instead.
134
- * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings.
135
- * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver
136
- * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object
137
- * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields
138
- * @param {boolean} [options.raw=false] Return document results as raw BSON buffers
139
- * @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
140
- * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST)
141
- * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys
142
- * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible
143
- * @param {object} [options.readConcern] Specify a read concern for the collection (only MongoDB 3.2 or higher supported)
144
- * @param {ReadConcernLevel} [options.readConcern.level='local'] Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported)
145
- * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed)
146
- * @param {string} [options.loggerLevel=undefined] The logging level (error/warn/info/debug)
147
- * @param {object} [options.logger=undefined] Custom logger object
148
- * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types
149
- * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers
150
- * @param {boolean} [options.promoteLongs=true] Promotes long values to number if they fit inside the 53 bits resolution
151
- * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit
152
- * @param {object} [options.validateOptions=false] Validate MongoClient passed in options for correctness
153
- * @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
154
- * @param {string} [options.auth.user=undefined] The username for auth
155
- * @param {string} [options.auth.password=undefined] The password for auth
156
- * @param {string} [options.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.
157
- * @param {object} [options.compression] Type of compression to use: snappy or zlib
158
- * @param {array} [options.readPreferenceTags] Read preference tags
159
- * @param {number} [options.numberOfRetries=5] The number of retries for a tailable cursor
160
- * @param {boolean} [options.auto_reconnect=true] Enable auto reconnecting for single server instances
161
- * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this client
162
- * @param {number} [options.minSize] If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections
163
- * @param {boolean} [options.useNewUrlParser=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.
164
- * @param {boolean} [options.useUnifiedTopology] Enables the new unified topology layer
165
- * @param {Number} [options.localThresholdMS=15] **Only applies to the unified topology** The size of the latency window for selecting among multiple suitable servers
166
- * @param {Number} [options.serverSelectionTimeoutMS=30000] **Only applies to the unified topology** How long to block for server selection before throwing an error
167
- * @param {Number} [options.heartbeatFrequencyMS=10000] **Only applies to the unified topology** The frequency with which topology updates are scheduled
168
- * @param {number} [options.maxPoolSize=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.
169
- * @param {number} [options.minPoolSize=0] **Only applies to the unified topology** The minimum number of connections that MUST exist at any moment in a single connection pool.
170
- * @param {number} [options.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.
171
- * @param {number} [options.waitQueueTimeoutMS=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.
172
- * @param {AutoEncryptionOptions} [options.autoEncryption] Optionally enable client side auto encryption.
93
+ * @typedef {object} MongoClientOptions
94
+ * @property {number} [poolSize] (**default**: 5) The maximum size of the individual server pool
95
+ * @property {boolean} [ssl] (**default**: false) Enable SSL connection. *deprecated* use `tls` variants
96
+ * @property {boolean} [sslValidate] (**default**: false) Validate mongod server certificate against Certificate Authority
97
+ * @property {buffer} [sslCA] (**default**: undefined) SSL Certificate store binary buffer *deprecated* use `tls` variants
98
+ * @property {buffer} [sslCert] (**default**: undefined) SSL Certificate binary buffer *deprecated* use `tls` variants
99
+ * @property {buffer} [sslKey] (**default**: undefined) SSL Key file binary buffer *deprecated* use `tls` variants
100
+ * @property {string} [sslPass] (**default**: undefined) SSL Certificate pass phrase *deprecated* use `tls` variants
101
+ * @property {buffer} [sslCRL] (**default**: undefined) SSL Certificate revocation list binary buffer *deprecated* use `tls` variants
102
+ * @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
103
+ * @property {boolean} [tls] (**default**: false) Enable TLS connections
104
+ * @property {boolean} [tlsInsecure] (**default**: false) Relax TLS constraints, disabling validation
105
+ * @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
106
+ * @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
107
+ * @property {string} [tlsCertificateKeyFilePassword] The password to decrypt the client private key to be used for TLS connections
108
+ * @property {boolean} [tlsAllowInvalidCertificates] Specifies whether or not the driver should error when the server’s TLS certificate is invalid
109
+ * @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
110
+ * @property {boolean} [autoReconnect] (**default**: true) Enable autoReconnect for single server instances
111
+ * @property {boolean} [noDelay] (**default**: true) TCP Connection no delay
112
+ * @property {boolean} [keepAlive] (**default**: true) TCP Connection keep alive enabled
113
+ * @property {number} [keepAliveInitialDelay] (**default**: 120000) The number of milliseconds to wait before initiating keepAlive on the TCP socket
114
+ * @property {number} [connectTimeoutMS] (**default**: 10000) How long to wait for a connection to be established before timing out
115
+ * @property {number} [socketTimeoutMS] (**default**: 0) How long a send or receive on a socket can take before timing out
116
+ * @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
117
+ * @property {number} [reconnectTries] (**default**: 30) Server attempt to reconnect #times
118
+ * @property {number} [reconnectInterval] (**default**: 1000) Server will wait # milliseconds between retries
119
+ * @property {boolean} [ha] (**default**: true) Control if high availability monitoring runs for Replicaset or Mongos proxies
120
+ * @property {number} [haInterval] (**default**: 10000) The High availability period for replicaset inquiry
121
+ * @property {string} [replicaSet] (**default**: undefined) The Replicaset set name
122
+ * @property {number} [secondaryAcceptableLatencyMS] (**default**: 15) Cutoff latency point in MS for Replicaset member selection
123
+ * @property {number} [acceptableLatencyMS] (**default**: 15) Cutoff latency point in MS for Mongos proxies selection
124
+ * @property {boolean} [connectWithNoPrimary] (**default**: false) Sets if the driver should connect even if no primary is available
125
+ * @property {string} [authSource] (**default**: undefined) Define the database to authenticate against
126
+ * @property {(number|string)} [w] **Deprecated** The write concern. Use writeConcern instead.
127
+ * @property {number} [wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead.
128
+ * @property {boolean} [j] (**default**: false) **Deprecated** Specify a journal write concern. Use writeConcern instead.
129
+ * @property {boolean} [fsync] (**default**: false) **Deprecated** Specify a file sync write concern. Use writeConcern instead.
130
+ * @property {object|WriteConcern} [writeConcern] Specify write concern settings.
131
+ * @property {boolean} [forceServerObjectId] (**default**: false) Force server to assign _id values instead of driver
132
+ * @property {boolean} [serializeFunctions] (**default**: false) Serialize functions on any object
133
+ * @property {Boolean} [ignoreUndefined] (**default**: false) Specify if the BSON serializer should ignore undefined fields
134
+ * @property {boolean} [raw] (**default**: false) Return document results as raw BSON buffers
135
+ * @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
136
+ * @property {(ReadPreference|string)} [readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST)
137
+ * @property {object} [pkFactory] A primary key factory object for generation of custom _id keys
138
+ * @property {object} [promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible
139
+ * @property {object} [readConcern] Specify a read concern for the collection (only MongoDB 3.2 or higher supported)
140
+ * @property {ReadConcernLevel} [readConcern.level] (**default**: {Level: 'local'}) Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported)
141
+ * @property {number} [maxStalenessSeconds] (**default**: undefined) The max staleness to secondary reads (values under 10 seconds cannot be guaranteed)
142
+ * @property {string} [loggerLevel] (**default**: undefined) The logging level (error/warn/info/debug)
143
+ * @property {object} [logger] (**default**: undefined) Custom logger object
144
+ * @property {boolean} [promoteValues] (**default**: true) Promotes BSON values to native types where possible, set to false to only receive wrapper types
145
+ * @property {boolean} [promoteBuffers] (**default**: false) Promotes Binary BSON values to native Node Buffers
146
+ * @property {boolean} [promoteLongs] (**default**: true) Promotes long values to number if they fit inside the 53 bits resolution
147
+ * @property {boolean} [domainsEnabled] (**default**: false) Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit
148
+ * @property {object} [validateOptions] (**default**: false) Validate MongoClient passed in options for correctness
149
+ * @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
150
+ * @property {string} [options.auth.user] (**default**: undefined) The username for auth
151
+ * @property {string} [options.auth.password] (**default**: undefined) The password for auth
152
+ * @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.
153
+ * @property {object} [compression] Type of compression to use: snappy or zlib
154
+ * @property {array} [readPreferenceTags] Read preference tags
155
+ * @property {number} [numberOfRetries] (**default**: 5) The number of retries for a tailable cursor
156
+ * @property {boolean} [auto_reconnect] (**default**: true) Enable auto reconnecting for single server instances
157
+ * @property {boolean} [monitorCommands] (**default**: false) Enable command monitoring for this client
158
+ * @property {number} [minSize] If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections
159
+ * @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.
160
+ * @property {boolean} [useUnifiedTopology] Enables the new unified topology layer
161
+ * @property {number} [localThresholdMS] (**default**: 15) **Only applies to the unified topology** The size of the latency window for selecting among multiple suitable servers
162
+ * @property {number} [serverSelectionTimeoutMS] (**default**: 30000) **Only applies to the unified topology** How long to block for server selection before throwing an error
163
+ * @property {number} [heartbeatFrequencyMS] (**default**: 10000) **Only applies to the unified topology** The frequency with which topology updates are scheduled
164
+ * @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.
165
+ * @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.
166
+ * @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.
167
+ * @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.
168
+ * @property {AutoEncryptionOptions} [autoEncryption] Optionally enable client side auto encryption.
173
169
  *
174
170
  * > 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
175
171
  * > (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.
@@ -181,10 +177,17 @@ const validOptions = require('./operations/connect').validOptions;
181
177
  * > - AutoEncryptionOptions.bypassAutomaticEncryption is false.
182
178
  * > 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.
183
179
  *
184
- * @param {DriverInfoOptions} [options.driverInfo] Allows a wrapping driver to amend the client metadata generated by the driver to include information about the wrapping driver
185
- * @param {boolean} [options.directConnection=false] Enable directConnection
186
- * @param {MongoClient~connectCallback} [callback] The command result callback
187
- * @return {MongoClient} a MongoClient instance
180
+ * @property {DriverInfoOptions} [driverInfo] Allows a wrapping driver to amend the client metadata generated by the driver to include information about the wrapping driver
181
+ * @property {boolean} [directConnection] (**default**: false) Enable directConnection
182
+ * @property {function} [callback] The command result callback
183
+ */
184
+
185
+ /**
186
+ * Creates a new MongoClient instance
187
+ * @constructor
188
+ * @extends {EventEmitter}
189
+ * @param {string} url The connection URI string
190
+ * @param {MongoClientOptions} [options] Optional settings
188
191
  */
189
192
  function MongoClient(url, options) {
190
193
  if (!(this instanceof MongoClient)) return new MongoClient(url, options);
@@ -382,86 +385,7 @@ MongoClient.prototype.isConnected = function(options) {
382
385
  * @method
383
386
  * @static
384
387
  * @param {string} url The connection URI string
385
- * @param {object} [options] Optional settings
386
- * @param {number} [options.poolSize=5] The maximum size of the individual server pool
387
- * @param {boolean} [options.ssl=false] Enable SSL connection. *deprecated* use `tls` variants
388
- * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against Certificate Authority
389
- * @param {buffer} [options.sslCA=undefined] SSL Certificate store binary buffer *deprecated* use `tls` variants
390
- * @param {buffer} [options.sslCert=undefined] SSL Certificate binary buffer *deprecated* use `tls` variants
391
- * @param {buffer} [options.sslKey=undefined] SSL Key file binary buffer *deprecated* use `tls` variants
392
- * @param {string} [options.sslPass=undefined] SSL Certificate pass phrase *deprecated* use `tls` variants
393
- * @param {buffer} [options.sslCRL=undefined] SSL Certificate revocation list binary buffer *deprecated* use `tls` variants
394
- * @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. *deprecated* use `tls` variants
395
- * @param {boolean} [options.tls=false] Enable TLS connections
396
- * @param {boolean} [options.tlsInsecure=false] Relax TLS constraints, disabling validation
397
- * @param {string} [options.tlsCAFile] A path to file with either a single or bundle of certificate authorities to be considered trusted when making a TLS connection
398
- * @param {string} [options.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
399
- * @param {string} [options.tlsCertificateKeyFilePassword] The password to decrypt the client private key to be used for TLS connections
400
- * @param {boolean} [options.tlsAllowInvalidCertificates] Specifies whether or not the driver should error when the server’s TLS certificate is invalid
401
- * @param {boolean} [options.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
402
- * @param {boolean} [options.autoReconnect=true] Enable autoReconnect for single server instances
403
- * @param {boolean} [options.noDelay=true] TCP Connection no delay
404
- * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled
405
- * @param {number} [options.keepAliveInitialDelay=120000] The number of milliseconds to wait before initiating keepAlive on the TCP socket
406
- * @param {number} [options.connectTimeoutMS=10000] How long to wait for a connection to be established before timing out
407
- * @param {number} [options.socketTimeoutMS=0] How long a send or receive on a socket can take before timing out
408
- * @param {number} [options.family] Version of IP stack. Can be 4, 6 or null (default).
409
- * If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure
410
- * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times
411
- * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries
412
- * @param {boolean} [options.ha=true] Control if high availability monitoring runs for Replicaset or Mongos proxies
413
- * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry
414
- * @param {string} [options.replicaSet=undefined] The Replicaset set name
415
- * @param {number} [options.secondaryAcceptableLatencyMS=15] Cutoff latency point in MS for Replicaset member selection
416
- * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for Mongos proxies selection
417
- * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available
418
- * @param {string} [options.authSource=undefined] Define the database to authenticate against
419
- * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead.
420
- * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead.
421
- * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead.
422
- * @param {boolean} [options.fsync=false] **Deprecated** Specify a file sync write concern. Use writeConcern instead.
423
- * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings.
424
- * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver
425
- * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object
426
- * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields
427
- * @param {boolean} [options.raw=false] Return document results as raw BSON buffers
428
- * @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
429
- * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST)
430
- * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys
431
- * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible
432
- * @param {object} [options.readConcern] Specify a read concern for the collection (only MongoDB 3.2 or higher supported)
433
- * @param {ReadConcernLevel} [options.readConcern.level='local'] Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported)
434
- * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed)
435
- * @param {string} [options.loggerLevel=undefined] The logging level (error/warn/info/debug)
436
- * @param {object} [options.logger=undefined] Custom logger object
437
- * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types
438
- * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers
439
- * @param {boolean} [options.promoteLongs=true] Promotes long values to number if they fit inside the 53 bits resolution
440
- * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit
441
- * @param {object} [options.validateOptions=false] Validate MongoClient passed in options for correctness
442
- * @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
443
- * @param {string} [options.auth.user=undefined] The username for auth
444
- * @param {string} [options.auth.password=undefined] The password for auth
445
- * @param {string} [options.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.
446
- * @param {object} [options.compression] Type of compression to use: snappy or zlib
447
- * @param {array} [options.readPreferenceTags] Read preference tags
448
- * @param {number} [options.numberOfRetries=5] The number of retries for a tailable cursor
449
- * @param {boolean} [options.auto_reconnect=true] Enable auto reconnecting for single server instances
450
- * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this client
451
- * @param {number} [options.minSize] If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections
452
- * @param {boolean} [options.directConnection=false] Enable directConnection
453
- * @param {boolean} [options.useNewUrlParser=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.
454
- * @param {boolean} [options.useUnifiedTopology] Enables the new unified topology layer
455
- * @param {Number} [options.localThresholdMS=15] **Only applies to the unified topology** The size of the latency window for selecting among multiple suitable servers
456
- * @param {Number} [options.serverSelectionTimeoutMS=30000] **Only applies to the unified topology** How long to block for server selection before throwing an error
457
- * @param {Number} [options.heartbeatFrequencyMS=10000] **Only applies to the unified topology** The frequency with which topology updates are scheduled
458
- * @param {number} [options.maxPoolSize=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.
459
- * @param {number} [options.minPoolSize=0] **Only applies to the unified topology** The minimum number of connections that MUST exist at any moment in a single connection pool.
460
- * @param {number} [options.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.
461
- * @param {number} [options.waitQueueTimeoutMS=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.
462
- * @param {AutoEncrypter~AutoEncryptionOptions} [options.autoEncryption] Optionally enable client side auto encryption
463
- * @param {DriverInfoOptions} [options.driverInfo] Allows a wrapping driver to amend the client metadata generated by the driver to include information about the wrapping driver
464
- * @param {MongoClient~connectCallback} [callback] The command result callback
388
+ * @param {MongoClientOptions} [options] Optional settings
465
389
  * @return {Promise<MongoClient>} returns Promise if no callback passed
466
390
  */
467
391
  MongoClient.connect = function(url, options, callback) {
@@ -70,14 +70,6 @@ class BulkWriteOperation extends OperationBase {
70
70
  return callback(err, null);
71
71
  }
72
72
 
73
- r.insertedCount = r.nInserted;
74
- r.matchedCount = r.nMatched;
75
- r.modifiedCount = r.nModified || 0;
76
- r.deletedCount = r.nRemoved;
77
- r.upsertedCount = r.getUpsertedIds().length;
78
- r.upsertedIds = {};
79
- r.insertedIds = {};
80
-
81
73
  // Update the n
82
74
  r.n = r.insertedCount;
83
75
 
@@ -569,7 +569,7 @@ function createUnifiedOptions(finalOptions, options) {
569
569
  'mongos_options'
570
570
  ];
571
571
  const noMerge = ['readconcern', 'compression', 'autoencryption'];
572
- const skip = ['w', 'wtimeout', 'j', 'journal', 'fsync', 'writeConcern'];
572
+ const skip = ['w', 'wtimeout', 'j', 'journal', 'fsync', 'writeconcern'];
573
573
 
574
574
  for (const name in options) {
575
575
  if (skip.indexOf(name.toLowerCase()) !== -1) {
@@ -1,16 +1,22 @@
1
1
  'use strict';
2
2
 
3
+ const MongoError = require('../core').MongoError;
3
4
  const FindAndModifyOperation = require('./find_and_modify');
4
5
  const hasAtomicOperators = require('../utils').hasAtomicOperators;
5
6
 
6
7
  class FindOneAndReplaceOperation extends FindAndModifyOperation {
7
8
  constructor(collection, filter, replacement, options) {
9
+ if ('returnDocument' in options && 'returnOriginal' in options) {
10
+ throw new MongoError(
11
+ 'findOneAndReplace option returnOriginal is deprecated in favor of returnDocument and cannot be combined'
12
+ );
13
+ }
8
14
  // Final options
9
15
  const finalOptions = Object.assign({}, options);
10
16
  finalOptions.fields = options.projection;
11
17
  finalOptions.update = true;
12
- finalOptions.new = options.returnOriginal !== void 0 ? !options.returnOriginal : false;
13
- finalOptions.upsert = options.upsert !== void 0 ? !!options.upsert : false;
18
+ finalOptions.new = options.returnDocument === 'after' || options.returnOriginal === false;
19
+ finalOptions.upsert = options.upsert === true;
14
20
 
15
21
  if (filter == null || typeof filter !== 'object') {
16
22
  throw new TypeError('Filter parameter must be an object');
@@ -1,17 +1,22 @@
1
1
  'use strict';
2
2
 
3
+ const MongoError = require('../core').MongoError;
3
4
  const FindAndModifyOperation = require('./find_and_modify');
4
5
  const hasAtomicOperators = require('../utils').hasAtomicOperators;
5
6
 
6
7
  class FindOneAndUpdateOperation extends FindAndModifyOperation {
7
8
  constructor(collection, filter, update, options) {
9
+ if ('returnDocument' in options && 'returnOriginal' in options) {
10
+ throw new MongoError(
11
+ 'findOneAndUpdate option returnOriginal is deprecated in favor of returnDocument and cannot be combined'
12
+ );
13
+ }
8
14
  // Final options
9
15
  const finalOptions = Object.assign({}, options);
10
16
  finalOptions.fields = options.projection;
11
17
  finalOptions.update = true;
12
- finalOptions.new =
13
- typeof options.returnOriginal === 'boolean' ? !options.returnOriginal : false;
14
- finalOptions.upsert = typeof options.upsert === 'boolean' ? options.upsert : false;
18
+ finalOptions.new = options.returnDocument === 'after' || options.returnOriginal === false;
19
+ finalOptions.upsert = options.upsert === true;
15
20
 
16
21
  if (filter == null || typeof filter !== 'object') {
17
22
  throw new TypeError('Filter parameter must be an object');
@@ -30,11 +30,7 @@ class InsertManyOperation extends OperationBase {
30
30
  docs = prepareDocs(coll, docs, options);
31
31
 
32
32
  // Generate the bulk write operations
33
- const operations = [
34
- {
35
- insertMany: docs
36
- }
37
- ];
33
+ const operations = docs.map(document => ({ insertOne: { document } }));
38
34
 
39
35
  const bulkWriteOperation = new BulkWriteOperation(coll, operations, options);
40
36
 
package/lib/utils.js CHANGED
@@ -40,7 +40,7 @@ var formatSortValue = (exports.formatSortValue = function(sortDirection) {
40
40
  });
41
41
 
42
42
  var formattedOrderClause = (exports.formattedOrderClause = function(sortValue) {
43
- var orderBy = {};
43
+ var orderBy = new Map();
44
44
  if (sortValue == null) return null;
45
45
  if (Array.isArray(sortValue)) {
46
46
  if (sortValue.length === 0) {
@@ -49,15 +49,22 @@ var formattedOrderClause = (exports.formattedOrderClause = function(sortValue) {
49
49
 
50
50
  for (var i = 0; i < sortValue.length; i++) {
51
51
  if (sortValue[i].constructor === String) {
52
- orderBy[sortValue[i]] = 1;
52
+ orderBy.set(`${sortValue[i]}`, 1);
53
53
  } else {
54
- orderBy[sortValue[i][0]] = formatSortValue(sortValue[i][1]);
54
+ orderBy.set(`${sortValue[i][0]}`, formatSortValue(sortValue[i][1]));
55
55
  }
56
56
  }
57
57
  } else if (sortValue != null && typeof sortValue === 'object') {
58
- orderBy = sortValue;
58
+ if (sortValue instanceof Map) {
59
+ orderBy = sortValue;
60
+ } else {
61
+ var sortKeys = Object.keys(sortValue);
62
+ for (var k of sortKeys) {
63
+ orderBy.set(k, sortValue[k]);
64
+ }
65
+ }
59
66
  } else if (typeof sortValue === 'string') {
60
- orderBy[sortValue] = 1;
67
+ orderBy.set(`${sortValue}`, 1);
61
68
  } else {
62
69
  throw new Error(
63
70
  'Illegal sort clause, must be of the form ' +
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mongodb",
3
- "version": "3.6.6",
3
+ "version": "3.6.7",
4
4
  "description": "The official MongoDB driver for Node.js",
5
5
  "main": "index.js",
6
6
  "files": [
@@ -40,33 +40,39 @@
40
40
  "bl": "^2.2.1",
41
41
  "bson": "^1.1.4",
42
42
  "denque": "^1.4.1",
43
- "optional-require": "^1.0.2",
43
+ "optional-require": "^1.0.3",
44
44
  "safe-buffer": "^5.1.2"
45
45
  },
46
46
  "devDependencies": {
47
+ "@types/chai": "^4.2.16",
48
+ "@types/mocha": "^8.2.2",
49
+ "@types/node": "^14.14.37",
50
+ "array-includes": "^3.1.3",
47
51
  "chai": "^4.1.1",
48
52
  "chai-subset": "^1.6.0",
49
53
  "chalk": "^2.4.2",
50
54
  "co": "4.6.0",
51
- "coveralls": "^2.11.6",
52
55
  "eslint": "^7.10.0",
53
56
  "eslint-config-prettier": "^6.11.0",
54
57
  "eslint-plugin-es": "^3.0.1",
55
58
  "eslint-plugin-prettier": "^3.1.3",
56
- "istanbul": "^0.4.5",
57
- "jsdoc": "3.5.5",
59
+ "jsdoc": "^3.5.5",
58
60
  "lodash.camelcase": "^4.3.0",
59
61
  "mocha": "5.2.0",
60
62
  "mocha-sinon": "^2.1.0",
61
63
  "mongodb-extjson": "^2.1.1",
62
64
  "mongodb-mock-server": "^1.0.1",
65
+ "nyc": "^15.1.0",
66
+ "object.entries": "^1.1.3",
63
67
  "prettier": "^1.19.1",
64
68
  "semver": "^5.5.0",
65
69
  "sinon": "^4.3.0",
66
70
  "sinon-chai": "^3.2.0",
67
71
  "snappy": "^6.3.4",
68
72
  "spec-xunit-file": "0.0.1-3",
69
- "standard-version": "^8.0.2",
73
+ "standard-version": "^9.2.0",
74
+ "tslib": "^2.2.0",
75
+ "typescript": "^4.2.4",
70
76
  "util.promisify": "^1.0.1",
71
77
  "worker-farm": "^1.5.0",
72
78
  "wtfnode": "^0.8.0",
@@ -80,18 +86,19 @@
80
86
  "url": "https://github.com/mongodb/node-mongodb-native/issues"
81
87
  },
82
88
  "scripts": {
83
- "atlas": "mocha --opts '{}' ./test/manual/atlas_connectivity.test.js",
89
+ "build:evergreen": "node .evergreen/generate_evergreen_tasks.js",
90
+ "build:unified": "tsc -p test/functional/unified-spec-runner/tsconfig.unified.json",
91
+ "check:atlas": "mocha --opts '{}' ./test/manual/atlas_connectivity.test.js",
92
+ "check:bench": "node test/benchmarks/driverBench/",
93
+ "check:coverage": "nyc npm run check:test",
84
94
  "check:kerberos": "mocha --opts '{}' -t 60000 test/manual/kerberos.test.js",
85
95
  "check:ldap": "mocha --opts '{}' test/manual/ldap.test.js",
96
+ "check:lint": "eslint -v && eslint lib test",
97
+ "check:test": "mocha --recursive test/functional test/unit",
86
98
  "check:tls": "mocha --opts '{}' test/manual/tls_support.test.js",
87
- "test": "npm run lint && mocha --recursive test/functional test/unit",
88
- "test-nolint": "mocha --recursive test/functional test/unit",
89
- "coverage": "istanbul cover mongodb-test-runner -- -t 60000 test/unit test/functional",
90
- "lint": "eslint -v && eslint lib test",
91
- "format": "npm run lint -- --fix",
92
- "bench": "node test/benchmarks/driverBench/",
93
- "generate-evergreen": "node .evergreen/generate_evergreen_tasks.js",
94
- "release": "standard-version -i HISTORY.md"
99
+ "format": "npm run check:lint -- --fix",
100
+ "release": "standard-version -i HISTORY.md",
101
+ "test": "npm run lint && mocha --recursive test/functional test/unit"
95
102
  },
96
103
  "homepage": "https://github.com/mongodb/node-mongodb-native",
97
104
  "optionalDependencies": {