mongodb 4.0.0 → 4.1.2

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.
Files changed (246) hide show
  1. package/README.md +62 -30
  2. package/lib/bson.js +1 -0
  3. package/lib/bson.js.map +1 -1
  4. package/lib/bulk/common.js +53 -30
  5. package/lib/bulk/common.js.map +1 -1
  6. package/lib/bulk/ordered.js +3 -2
  7. package/lib/bulk/ordered.js.map +1 -1
  8. package/lib/bulk/unordered.js +3 -2
  9. package/lib/bulk/unordered.js.map +1 -1
  10. package/lib/change_stream.js +23 -13
  11. package/lib/change_stream.js.map +1 -1
  12. package/lib/cmap/auth/auth_provider.js +2 -1
  13. package/lib/cmap/auth/auth_provider.js.map +1 -1
  14. package/lib/cmap/auth/gssapi.js +5 -4
  15. package/lib/cmap/auth/gssapi.js.map +1 -1
  16. package/lib/cmap/auth/mongo_credentials.js +9 -5
  17. package/lib/cmap/auth/mongo_credentials.js.map +1 -1
  18. package/lib/cmap/auth/mongocr.js +2 -2
  19. package/lib/cmap/auth/mongocr.js.map +1 -1
  20. package/lib/cmap/auth/mongodb_aws.js +32 -32
  21. package/lib/cmap/auth/mongodb_aws.js.map +1 -1
  22. package/lib/cmap/auth/plain.js +1 -1
  23. package/lib/cmap/auth/plain.js.map +1 -1
  24. package/lib/cmap/auth/scram.js +15 -12
  25. package/lib/cmap/auth/scram.js.map +1 -1
  26. package/lib/cmap/auth/x509.js +2 -2
  27. package/lib/cmap/auth/x509.js.map +1 -1
  28. package/lib/cmap/command_monitoring_events.js +26 -10
  29. package/lib/cmap/command_monitoring_events.js.map +1 -1
  30. package/lib/cmap/commands.js +9 -5
  31. package/lib/cmap/commands.js.map +1 -1
  32. package/lib/cmap/connect.js +23 -9
  33. package/lib/cmap/connect.js.map +1 -1
  34. package/lib/cmap/connection.js +43 -46
  35. package/lib/cmap/connection.js.map +1 -1
  36. package/lib/cmap/connection_pool.js +113 -15
  37. package/lib/cmap/connection_pool.js.map +1 -1
  38. package/lib/cmap/connection_pool_events.js +3 -1
  39. package/lib/cmap/connection_pool_events.js.map +1 -1
  40. package/lib/cmap/errors.js +3 -3
  41. package/lib/cmap/errors.js.map +1 -1
  42. package/lib/cmap/message_stream.js +1 -1
  43. package/lib/cmap/message_stream.js.map +1 -1
  44. package/lib/cmap/metrics.js +62 -0
  45. package/lib/cmap/metrics.js.map +1 -0
  46. package/lib/cmap/stream_description.js +3 -1
  47. package/lib/cmap/stream_description.js.map +1 -1
  48. package/lib/cmap/wire_protocol/compression.js +22 -9
  49. package/lib/cmap/wire_protocol/compression.js.map +1 -1
  50. package/lib/cmap/wire_protocol/shared.js +1 -1
  51. package/lib/cmap/wire_protocol/shared.js.map +1 -1
  52. package/lib/collection.js +23 -18
  53. package/lib/collection.js.map +1 -1
  54. package/lib/connection_string.js +76 -30
  55. package/lib/connection_string.js.map +1 -1
  56. package/lib/cursor/abstract_cursor.js +75 -68
  57. package/lib/cursor/abstract_cursor.js.map +1 -1
  58. package/lib/cursor/aggregation_cursor.js +47 -9
  59. package/lib/cursor/aggregation_cursor.js.map +1 -1
  60. package/lib/cursor/find_cursor.js +53 -13
  61. package/lib/cursor/find_cursor.js.map +1 -1
  62. package/lib/db.js +21 -14
  63. package/lib/db.js.map +1 -1
  64. package/lib/deps.js +16 -5
  65. package/lib/deps.js.map +1 -1
  66. package/lib/encrypter.js +5 -8
  67. package/lib/encrypter.js.map +1 -1
  68. package/lib/error.js +230 -34
  69. package/lib/error.js.map +1 -1
  70. package/lib/explain.js +2 -2
  71. package/lib/explain.js.map +1 -1
  72. package/lib/gridfs/download.js +22 -47
  73. package/lib/gridfs/download.js.map +1 -1
  74. package/lib/gridfs/index.js +4 -3
  75. package/lib/gridfs/index.js.map +1 -1
  76. package/lib/gridfs/upload.js +13 -21
  77. package/lib/gridfs/upload.js.map +1 -1
  78. package/lib/index.js +27 -2
  79. package/lib/index.js.map +1 -1
  80. package/lib/logger.js +3 -2
  81. package/lib/logger.js.map +1 -1
  82. package/lib/mongo_client.js +5 -8
  83. package/lib/mongo_client.js.map +1 -1
  84. package/lib/mongo_types.js.map +1 -1
  85. package/lib/operations/add_user.js +2 -3
  86. package/lib/operations/add_user.js.map +1 -1
  87. package/lib/operations/aggregate.js +12 -9
  88. package/lib/operations/aggregate.js.map +1 -1
  89. package/lib/operations/command.js +5 -7
  90. package/lib/operations/command.js.map +1 -1
  91. package/lib/operations/common_functions.js +1 -1
  92. package/lib/operations/common_functions.js.map +1 -1
  93. package/lib/operations/connect.js +3 -2
  94. package/lib/operations/connect.js.map +1 -1
  95. package/lib/operations/count.js +1 -1
  96. package/lib/operations/count.js.map +1 -1
  97. package/lib/operations/count_documents.js +1 -1
  98. package/lib/operations/count_documents.js.map +1 -1
  99. package/lib/operations/delete.js +5 -5
  100. package/lib/operations/delete.js.map +1 -1
  101. package/lib/operations/distinct.js +2 -2
  102. package/lib/operations/distinct.js.map +1 -1
  103. package/lib/operations/estimated_document_count.js +5 -1
  104. package/lib/operations/estimated_document_count.js.map +1 -1
  105. package/lib/operations/eval.js.map +1 -1
  106. package/lib/operations/execute_operation.js +31 -17
  107. package/lib/operations/execute_operation.js.map +1 -1
  108. package/lib/operations/find.js +13 -9
  109. package/lib/operations/find.js.map +1 -1
  110. package/lib/operations/find_and_modify.js +9 -9
  111. package/lib/operations/find_and_modify.js.map +1 -1
  112. package/lib/operations/indexes.js +8 -3
  113. package/lib/operations/indexes.js.map +1 -1
  114. package/lib/operations/insert.js +5 -3
  115. package/lib/operations/insert.js.map +1 -1
  116. package/lib/operations/is_capped.js +2 -1
  117. package/lib/operations/is_capped.js.map +1 -1
  118. package/lib/operations/list_collections.js +6 -3
  119. package/lib/operations/list_collections.js.map +1 -1
  120. package/lib/operations/map_reduce.js +1 -1
  121. package/lib/operations/map_reduce.js.map +1 -1
  122. package/lib/operations/operation.js +3 -1
  123. package/lib/operations/operation.js.map +1 -1
  124. package/lib/operations/options_operation.js +2 -1
  125. package/lib/operations/options_operation.js.map +1 -1
  126. package/lib/operations/profiling_level.js +4 -2
  127. package/lib/operations/profiling_level.js.map +1 -1
  128. package/lib/operations/set_profiling_level.js +4 -2
  129. package/lib/operations/set_profiling_level.js.map +1 -1
  130. package/lib/operations/update.js +12 -12
  131. package/lib/operations/update.js.map +1 -1
  132. package/lib/operations/validate_collection.js +6 -5
  133. package/lib/operations/validate_collection.js.map +1 -1
  134. package/lib/promise_provider.js +1 -1
  135. package/lib/promise_provider.js.map +1 -1
  136. package/lib/read_preference.js +8 -8
  137. package/lib/read_preference.js.map +1 -1
  138. package/lib/sdam/common.js +12 -10
  139. package/lib/sdam/common.js.map +1 -1
  140. package/lib/sdam/server.js +90 -25
  141. package/lib/sdam/server.js.map +1 -1
  142. package/lib/sdam/server_description.js +9 -4
  143. package/lib/sdam/server_description.js.map +1 -1
  144. package/lib/sdam/server_selection.js +10 -4
  145. package/lib/sdam/server_selection.js.map +1 -1
  146. package/lib/sdam/srv_polling.js +1 -1
  147. package/lib/sdam/srv_polling.js.map +1 -1
  148. package/lib/sdam/topology.js +42 -21
  149. package/lib/sdam/topology.js.map +1 -1
  150. package/lib/sdam/topology_description.js +7 -3
  151. package/lib/sdam/topology_description.js.map +1 -1
  152. package/lib/sessions.js +132 -31
  153. package/lib/sessions.js.map +1 -1
  154. package/lib/sort.js +3 -3
  155. package/lib/sort.js.map +1 -1
  156. package/lib/transactions.js +15 -7
  157. package/lib/transactions.js.map +1 -1
  158. package/lib/utils.js +60 -20
  159. package/lib/utils.js.map +1 -1
  160. package/mongodb.d.ts +523 -138
  161. package/mongodb.ts34.d.ts +480 -141
  162. package/package.json +44 -48
  163. package/src/bson.ts +1 -0
  164. package/src/bulk/common.ts +83 -43
  165. package/src/bulk/ordered.ts +4 -3
  166. package/src/bulk/unordered.ts +4 -3
  167. package/src/change_stream.ts +46 -29
  168. package/src/cmap/auth/auth_provider.ts +3 -2
  169. package/src/cmap/auth/gssapi.ts +15 -5
  170. package/src/cmap/auth/mongo_credentials.ts +22 -8
  171. package/src/cmap/auth/mongocr.ts +3 -3
  172. package/src/cmap/auth/mongodb_aws.ts +52 -39
  173. package/src/cmap/auth/plain.ts +2 -2
  174. package/src/cmap/auth/scram.ts +23 -13
  175. package/src/cmap/auth/x509.ts +3 -3
  176. package/src/cmap/command_monitoring_events.ts +36 -14
  177. package/src/cmap/commands.ts +12 -6
  178. package/src/cmap/connect.ts +42 -12
  179. package/src/cmap/connection.ts +54 -62
  180. package/src/cmap/connection_pool.ts +141 -20
  181. package/src/cmap/connection_pool_events.ts +8 -1
  182. package/src/cmap/errors.ts +3 -4
  183. package/src/cmap/message_stream.ts +2 -4
  184. package/src/cmap/metrics.ts +58 -0
  185. package/src/cmap/stream_description.ts +6 -1
  186. package/src/cmap/wire_protocol/compression.ts +26 -13
  187. package/src/cmap/wire_protocol/shared.ts +4 -2
  188. package/src/collection.ts +75 -70
  189. package/src/connection_string.ts +97 -34
  190. package/src/cursor/abstract_cursor.ts +141 -104
  191. package/src/cursor/aggregation_cursor.ts +34 -20
  192. package/src/cursor/find_cursor.ts +41 -21
  193. package/src/db.ts +19 -18
  194. package/src/deps.ts +110 -22
  195. package/src/encrypter.ts +6 -12
  196. package/src/error.ts +264 -48
  197. package/src/explain.ts +3 -3
  198. package/src/gridfs/download.ts +48 -53
  199. package/src/gridfs/index.ts +5 -4
  200. package/src/gridfs/upload.ts +32 -33
  201. package/src/index.ts +42 -4
  202. package/src/logger.ts +6 -3
  203. package/src/mongo_client.ts +20 -23
  204. package/src/mongo_types.ts +19 -20
  205. package/src/operations/add_user.ts +4 -5
  206. package/src/operations/aggregate.ts +18 -17
  207. package/src/operations/command.ts +7 -10
  208. package/src/operations/common_functions.ts +2 -3
  209. package/src/operations/connect.ts +4 -3
  210. package/src/operations/count.ts +2 -2
  211. package/src/operations/count_documents.ts +2 -2
  212. package/src/operations/delete.ts +8 -6
  213. package/src/operations/distinct.ts +5 -3
  214. package/src/operations/estimated_document_count.ts +5 -1
  215. package/src/operations/eval.ts +1 -1
  216. package/src/operations/execute_operation.ts +41 -20
  217. package/src/operations/find.ts +25 -16
  218. package/src/operations/find_and_modify.ts +12 -10
  219. package/src/operations/indexes.ts +39 -8
  220. package/src/operations/insert.ts +7 -4
  221. package/src/operations/is_capped.ts +3 -2
  222. package/src/operations/list_collections.ts +9 -6
  223. package/src/operations/map_reduce.ts +4 -2
  224. package/src/operations/operation.ts +7 -2
  225. package/src/operations/options_operation.ts +3 -2
  226. package/src/operations/profiling_level.ts +5 -3
  227. package/src/operations/set_profiling_level.ts +9 -3
  228. package/src/operations/update.ts +17 -13
  229. package/src/operations/validate_collection.ts +7 -6
  230. package/src/promise_provider.ts +2 -2
  231. package/src/read_preference.ts +11 -9
  232. package/src/sdam/common.ts +11 -9
  233. package/src/sdam/server.ts +168 -69
  234. package/src/sdam/server_description.ts +16 -4
  235. package/src/sdam/server_selection.ts +15 -7
  236. package/src/sdam/srv_polling.ts +2 -2
  237. package/src/sdam/topology.ts +67 -36
  238. package/src/sdam/topology_description.ts +11 -4
  239. package/src/sessions.ts +194 -37
  240. package/src/sort.ts +6 -4
  241. package/src/transactions.ts +18 -9
  242. package/src/utils.ts +73 -20
  243. package/HISTORY.md +0 -2993
  244. package/lib/operations/find_one.js +0 -34
  245. package/lib/operations/find_one.js.map +0 -1
  246. package/src/operations/find_one.ts +0 -43
@@ -95,11 +95,11 @@ export interface FilterOperators<TValue> extends Document {
95
95
  $eq?: TValue;
96
96
  $gt?: TValue;
97
97
  $gte?: TValue;
98
- $in?: TValue[];
98
+ $in?: ReadonlyArray<TValue>;
99
99
  $lt?: TValue;
100
100
  $lte?: TValue;
101
101
  $ne?: TValue;
102
- $nin?: TValue[];
102
+ $nin?: ReadonlyArray<TValue>;
103
103
  // Logical
104
104
  $not?: TValue extends string ? FilterOperators<TValue> | RegExp : FilterOperators<TValue>;
105
105
  // Element
@@ -122,8 +122,8 @@ export interface FilterOperators<TValue> extends Document {
122
122
  $nearSphere?: Document;
123
123
  $maxDistance?: number;
124
124
  // Array
125
- $all?: TValue extends ReadonlyArray<any> ? any[] : never;
126
- $elemMatch?: TValue extends ReadonlyArray<any> ? Document : never;
125
+ $all?: ReadonlyArray<any>;
126
+ $elemMatch?: Document;
127
127
  $size?: TValue extends ReadonlyArray<any> ? number : never;
128
128
  // Bitwise
129
129
  $bitsAllClear?: BitwiseFilter;
@@ -137,7 +137,7 @@ export interface FilterOperators<TValue> extends Document {
137
137
  export type BitwiseFilter =
138
138
  | number /** numeric bit mask */
139
139
  | Binary /** BinData bit mask */
140
- | number[]; /** `[ <position1>, <position2>, ... ]` */
140
+ | ReadonlyArray<number>; /** `[ <position1>, <position2>, ... ]` */
141
141
 
142
142
  /** @public */
143
143
  export const BSONType = Object.freeze({
@@ -169,20 +169,19 @@ export type BSONType = typeof BSONType[keyof typeof BSONType];
169
169
  /** @public */
170
170
  export type BSONTypeAlias = keyof typeof BSONType;
171
171
 
172
- /** @public */
173
- export interface ProjectionOperators extends Document {
174
- $elemMatch?: Document;
175
- $slice?: number | [number, number];
176
- $meta?: string;
177
- /** @deprecated Since MongoDB 3.2, Use FindCursor#max */
178
- $max?: any;
179
- }
172
+ /**
173
+ * @public
174
+ * Projection is flexible to permit the wide array of aggregation operators
175
+ * @deprecated since v4.1.0: Since projections support all aggregation operations we have no plans to narrow this type further
176
+ */
177
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
178
+ export type Projection<TSchema extends Document = Document> = Document;
180
179
 
181
- /** @public */
182
- export type Projection<TSchema> = {
183
- [Key in keyof TSchema]?: ProjectionOperators | 0 | 1 | boolean;
184
- } &
185
- Partial<Record<string, ProjectionOperators | 0 | 1 | boolean>>;
180
+ /**
181
+ * @public
182
+ * @deprecated since v4.1.0: Since projections support all aggregation operations we have no plans to narrow this type further
183
+ */
184
+ export type ProjectionOperators = Document;
186
185
 
187
186
  /** @public */
188
187
  export type IsAny<Type, ResultIfAny, ResultIfNotAny> = true extends false & Type
@@ -286,7 +285,7 @@ export type PullAllOperator<TSchema> = ({
286
285
  readonly [key in KeysOfAType<TSchema, ReadonlyArray<any>>]?: TSchema[key];
287
286
  } &
288
287
  NotAcceptedFields<TSchema, ReadonlyArray<any>>) & {
289
- readonly [key: string]: any[];
288
+ readonly [key: string]: ReadonlyArray<any>;
290
289
  };
291
290
 
292
291
  /** @public */
@@ -320,7 +319,7 @@ export type UpdateFilter<TSchema> = {
320
319
  export type Nullable<AnyType> = AnyType | null | undefined;
321
320
 
322
321
  /** @public */
323
- export type OneOrMore<T> = T | T[];
322
+ export type OneOrMore<T> = T | ReadonlyArray<T>;
324
323
 
325
324
  /** @public */
326
325
  export type GenericListener = (...args: any[]) => void;
@@ -1,7 +1,7 @@
1
1
  import * as crypto from 'crypto';
2
2
  import { Aspect, defineAspects } from './operation';
3
3
  import { CommandOperation, CommandOperationOptions } from './command';
4
- import { MongoDriverError } from '../error';
4
+ import { MongoInvalidArgumentError } from '../error';
5
5
  import { Callback, emitWarningOnce, getTopology } from '../utils';
6
6
  import type { Document } from '../bson';
7
7
  import type { Server } from '../sdam/server';
@@ -54,9 +54,8 @@ export class AddUserOperation extends CommandOperation<Document> {
54
54
  // Error out if digestPassword set
55
55
  if (options.digestPassword != null) {
56
56
  return callback(
57
- new MongoDriverError(
58
- 'The digestPassword option is not supported via add_user. ' +
59
- "Please use db.command('createUser', ...) instead for this option."
57
+ new MongoInvalidArgumentError(
58
+ 'Option "digestPassword" not supported via addUser, use db.command(...) instead'
60
59
  )
61
60
  );
62
61
  }
@@ -83,7 +82,7 @@ export class AddUserOperation extends CommandOperation<Document> {
83
82
  // Use node md5 generator
84
83
  const md5 = crypto.createHash('md5');
85
84
  // Generate keys used for authentication
86
- md5.update(username + ':mongo:' + password);
85
+ md5.update(`${username}:mongo:${password}`);
87
86
  userPassword = md5.digest('hex');
88
87
  }
89
88
 
@@ -1,12 +1,7 @@
1
- import {
2
- CommandOperation,
3
- CommandOperationOptions,
4
- OperationParent,
5
- CollationOptions
6
- } from './command';
1
+ import { CommandOperation, CommandOperationOptions, CollationOptions } from './command';
7
2
  import { ReadPreference } from '../read_preference';
8
- import { MongoDriverError } from '../error';
9
- import { maxWireVersion } from '../utils';
3
+ import { MongoInvalidArgumentError } from '../error';
4
+ import { maxWireVersion, MongoDBNamespace } from '../utils';
10
5
  import { Aspect, defineAspects, Hint } from './operation';
11
6
  import type { Callback } from '../utils';
12
7
  import type { Document } from '../bson';
@@ -47,14 +42,13 @@ export class AggregateOperation<T = Document> extends CommandOperation<T> {
47
42
  pipeline: Document[];
48
43
  hasWriteStage: boolean;
49
44
 
50
- constructor(parent: OperationParent, pipeline: Document[], options?: AggregateOptions) {
51
- super(parent, options);
45
+ constructor(ns: MongoDBNamespace, pipeline: Document[], options?: AggregateOptions) {
46
+ super(undefined, { ...options, dbName: ns.db });
52
47
 
53
48
  this.options = options ?? {};
54
- this.target =
55
- parent.s.namespace && parent.s.namespace.collection
56
- ? parent.s.namespace.collection
57
- : DB_AGGREGATE_COLLECTION;
49
+
50
+ // Covers when ns.collection is null, undefined or the empty string, use DB_AGGREGATE_COLLECTION
51
+ this.target = ns.collection || DB_AGGREGATE_COLLECTION;
58
52
 
59
53
  this.pipeline = pipeline;
60
54
 
@@ -75,11 +69,13 @@ export class AggregateOperation<T = Document> extends CommandOperation<T> {
75
69
  }
76
70
 
77
71
  if (this.explain && this.writeConcern) {
78
- throw new MongoDriverError('"explain" cannot be used on an aggregate call with writeConcern');
72
+ throw new MongoInvalidArgumentError(
73
+ 'Option "explain" cannot be used on an aggregate call with writeConcern'
74
+ );
79
75
  }
80
76
 
81
77
  if (options?.cursor != null && typeof options.cursor !== 'object') {
82
- throw new MongoDriverError('cursor options must be an object');
78
+ throw new MongoInvalidArgumentError('Cursor options must be an object');
83
79
  }
84
80
  }
85
81
 
@@ -131,4 +127,9 @@ export class AggregateOperation<T = Document> extends CommandOperation<T> {
131
127
  }
132
128
  }
133
129
 
134
- defineAspects(AggregateOperation, [Aspect.READ_OPERATION, Aspect.RETRYABLE, Aspect.EXPLAINABLE]);
130
+ defineAspects(AggregateOperation, [
131
+ Aspect.READ_OPERATION,
132
+ Aspect.RETRYABLE,
133
+ Aspect.EXPLAINABLE,
134
+ Aspect.CURSOR_CREATING
135
+ ]);
@@ -4,7 +4,7 @@ import { WriteConcern, WriteConcernOptions } from '../write_concern';
4
4
  import { maxWireVersion, MongoDBNamespace, Callback, decorateWithExplain } from '../utils';
5
5
  import type { ReadPreference } from '../read_preference';
6
6
  import { ClientSession, commandSupportsReadConcern } from '../sessions';
7
- import { MongoDriverError } from '../error';
7
+ import { MongoInvalidArgumentError, MongoCompatibilityError } from '../error';
8
8
  import type { Logger } from '../logger';
9
9
  import type { Server } from '../sdam/server';
10
10
  import type { BSONSerializeOptions, Document } from '../bson';
@@ -31,7 +31,7 @@ export interface CommandOperationOptions
31
31
  extends OperationOptions,
32
32
  WriteConcernOptions,
33
33
  ExplainOptions {
34
- /** Return the full server response for the command */
34
+ /** @deprecated This option does nothing */
35
35
  fullResponse?: boolean;
36
36
  /** Specify a read concern and level for the collection. (only MongoDB 3.2 or higher supported) */
37
37
  readConcern?: ReadConcernLike;
@@ -66,7 +66,6 @@ export abstract class CommandOperation<T> extends AbstractOperation<T> {
66
66
  readConcern?: ReadConcern;
67
67
  writeConcern?: WriteConcern;
68
68
  explain?: Explain;
69
- fullResponse?: boolean;
70
69
  logger?: Logger;
71
70
 
72
71
  constructor(parent?: OperationParent, options?: CommandOperationOptions) {
@@ -87,8 +86,6 @@ export abstract class CommandOperation<T> extends AbstractOperation<T> {
87
86
 
88
87
  this.readConcern = ReadConcern.fromOptions(options);
89
88
  this.writeConcern = WriteConcern.fromOptions(options);
90
- this.fullResponse =
91
- options && typeof options.fullResponse === 'boolean' ? options.fullResponse : false;
92
89
 
93
90
  // TODO(NODE-2056): make logger another "inheritable" property
94
91
  if (parent && parent.logger) {
@@ -97,14 +94,14 @@ export abstract class CommandOperation<T> extends AbstractOperation<T> {
97
94
 
98
95
  if (this.hasAspect(Aspect.EXPLAINABLE)) {
99
96
  this.explain = Explain.fromOptions(options);
100
- } else if (options?.explain !== undefined) {
101
- throw new MongoDriverError(`explain is not supported on this command`);
97
+ } else if (options?.explain != null) {
98
+ throw new MongoInvalidArgumentError(`Option "explain" is not supported on this command`);
102
99
  }
103
100
  }
104
101
 
105
102
  get canRetryWrite(): boolean {
106
103
  if (this.hasAspect(Aspect.EXPLAINABLE)) {
107
- return this.explain === undefined;
104
+ return this.explain == null;
108
105
  }
109
106
  return true;
110
107
  }
@@ -131,7 +128,7 @@ export abstract class CommandOperation<T> extends AbstractOperation<T> {
131
128
 
132
129
  if (options.collation && serverWireVersion < SUPPORTS_WRITE_CONCERN_AND_COLLATION) {
133
130
  callback(
134
- new MongoDriverError(
131
+ new MongoCompatibilityError(
135
132
  `Server ${server.name}, which reports wire version ${serverWireVersion}, does not support collation`
136
133
  )
137
134
  );
@@ -169,6 +166,6 @@ export abstract class CommandOperation<T> extends AbstractOperation<T> {
169
166
  }
170
167
  }
171
168
 
172
- server.command(this.ns, cmd, { fullResult: !!this.fullResponse, ...options }, callback);
169
+ server.command(this.ns, cmd, options, callback);
173
170
  }
174
171
  }
@@ -1,4 +1,4 @@
1
- import { MongoDriverError } from '../error';
1
+ import { MongoTopologyClosedError } from '../error';
2
2
  import { Callback, getTopology } from '../utils';
3
3
  import type { Document } from '../bson';
4
4
  import type { Db } from '../db';
@@ -41,8 +41,7 @@ export function indexInformation(
41
41
  const full = options.full == null ? false : options.full;
42
42
 
43
43
  // Did the user destroy the topology
44
- if (getTopology(db).isDestroyed())
45
- return callback(new MongoDriverError('topology was destroyed'));
44
+ if (getTopology(db).isDestroyed()) return callback(new MongoTopologyClosedError());
46
45
  // Process all the results from the index command and collection
47
46
  function processResults(indexes: any) {
48
47
  // Contains all the information
@@ -1,4 +1,4 @@
1
- import { MongoDriverError } from '../error';
1
+ import { MongoRuntimeError, MongoInvalidArgumentError } from '../error';
2
2
  import { Topology, TOPOLOGY_EVENTS } from '../sdam/topology';
3
3
  import { resolveSRVRecord } from '../connection_string';
4
4
  import type { Callback } from '../utils';
@@ -21,7 +21,7 @@ export function connect(
21
21
  callback: Callback<MongoClient>
22
22
  ): void {
23
23
  if (!callback) {
24
- throw new MongoDriverError('no callback function provided');
24
+ throw new MongoInvalidArgumentError('Callback function must be provided');
25
25
  }
26
26
 
27
27
  // If a connection already been established, we can terminate early
@@ -41,7 +41,8 @@ export function connect(
41
41
  }
42
42
 
43
43
  // Return a more specific error message for MongoClient.connect
44
- return callback(new MongoDriverError(warningMessage));
44
+ // TODO(NODE-3483)
45
+ return callback(new MongoRuntimeError(warningMessage));
45
46
  }
46
47
 
47
48
  callback(err, mongoClient);
@@ -25,7 +25,7 @@ export class CountOperation extends CommandOperation<number> {
25
25
  query: Document;
26
26
 
27
27
  constructor(namespace: MongoDBNamespace, filter: Document, options: CountOptions) {
28
- super(({ s: { namespace: namespace } } as unknown) as Collection, options);
28
+ super({ s: { namespace: namespace } } as unknown as Collection, options);
29
29
 
30
30
  this.options = options;
31
31
  this.collectionName = namespace.collection;
@@ -47,7 +47,7 @@ export class CountOperation extends CommandOperation<number> {
47
47
  cmd.skip = options.skip;
48
48
  }
49
49
 
50
- if (typeof options.hint !== 'undefined') {
50
+ if (options.hint != null) {
51
51
  cmd.hint = options.hint;
52
52
  }
53
53
 
@@ -29,7 +29,7 @@ export class CountDocumentsOperation extends AggregateOperation<number> {
29
29
 
30
30
  pipeline.push({ $group: { _id: 1, n: { $sum: 1 } } });
31
31
 
32
- super(collection, pipeline, options);
32
+ super(collection.s.namespace, pipeline, options);
33
33
  }
34
34
 
35
35
  execute(server: Server, session: ClientSession, callback: Callback<number>): void {
@@ -40,7 +40,7 @@ export class CountDocumentsOperation extends AggregateOperation<number> {
40
40
  }
41
41
 
42
42
  // NOTE: We're avoiding creating a cursor here to reduce the callstack.
43
- const response = (result as unknown) as Document;
43
+ const response = result as unknown as Document;
44
44
  if (response.cursor == null || response.cursor.firstBatch == null) {
45
45
  callback(undefined, 0);
46
46
  return;
@@ -5,7 +5,7 @@ import type { Document } from '../bson';
5
5
  import type { Server } from '../sdam/server';
6
6
  import type { Collection } from '../collection';
7
7
  import type { ClientSession } from '../sessions';
8
- import { MongoDriverError, MongoServerError } from '../error';
8
+ import { MongoServerError, MongoCompatibilityError } from '../error';
9
9
  import type { WriteConcernOptions } from '../write_concern';
10
10
 
11
11
  /** @public */
@@ -64,7 +64,7 @@ export class DeleteOperation extends CommandOperation<Document> {
64
64
  return false;
65
65
  }
66
66
 
67
- return this.statements.every(op => (typeof op.limit !== 'undefined' ? op.limit > 0 : true));
67
+ return this.statements.every(op => (op.limit != null ? op.limit > 0 : true));
68
68
  }
69
69
 
70
70
  execute(server: Server, session: ClientSession, callback: Callback): void {
@@ -80,23 +80,25 @@ export class DeleteOperation extends CommandOperation<Document> {
80
80
  command.let = options.let;
81
81
  }
82
82
 
83
- if (options.explain !== undefined && maxWireVersion(server) < 3) {
83
+ if (options.explain != null && maxWireVersion(server) < 3) {
84
84
  return callback
85
- ? callback(new MongoDriverError(`server ${server.name} does not support explain on delete`))
85
+ ? callback(
86
+ new MongoCompatibilityError(`Server ${server.name} does not support explain on delete`)
87
+ )
86
88
  : undefined;
87
89
  }
88
90
 
89
91
  const unacknowledgedWrite = this.writeConcern && this.writeConcern.w === 0;
90
92
  if (unacknowledgedWrite || maxWireVersion(server) < 5) {
91
93
  if (this.statements.find((o: Document) => o.hint)) {
92
- callback(new MongoDriverError(`servers < 3.4 do not support hint on delete`));
94
+ callback(new MongoCompatibilityError(`Servers < 3.4 do not support hint on delete`));
93
95
  return;
94
96
  }
95
97
  }
96
98
 
97
99
  const statementWithCollation = this.statements.find(statement => !!statement.collation);
98
100
  if (statementWithCollation && collationNotSupported(server, statementWithCollation)) {
99
- callback(new MongoDriverError(`server ${server.name} does not support collation`));
101
+ callback(new MongoCompatibilityError(`Server ${server.name} does not support collation`));
100
102
  return;
101
103
  }
102
104
 
@@ -4,7 +4,7 @@ import { decorateWithCollation, decorateWithReadConcern, Callback, maxWireVersio
4
4
  import type { Document } from '../bson';
5
5
  import type { Server } from '../sdam/server';
6
6
  import type { Collection } from '../collection';
7
- import { MongoDriverError } from '../error';
7
+ import { MongoCompatibilityError } from '../error';
8
8
  import type { ClientSession } from '../sessions';
9
9
 
10
10
  /** @public */
@@ -68,7 +68,9 @@ export class DistinctOperation extends CommandOperation<any[]> {
68
68
  }
69
69
 
70
70
  if (this.explain && maxWireVersion(server) < 4) {
71
- callback(new MongoDriverError(`server ${server.name} does not support explain on distinct`));
71
+ callback(
72
+ new MongoCompatibilityError(`Server ${server.name} does not support explain on distinct`)
73
+ );
72
74
  return;
73
75
  }
74
76
 
@@ -78,7 +80,7 @@ export class DistinctOperation extends CommandOperation<any[]> {
78
80
  return;
79
81
  }
80
82
 
81
- callback(undefined, this.options.fullResponse || this.explain ? result : result.values);
83
+ callback(undefined, this.explain ? result : result.values);
82
84
  });
83
85
  }
84
86
  }
@@ -68,4 +68,8 @@ export class EstimatedDocumentCountOperation extends CommandOperation<number> {
68
68
  }
69
69
  }
70
70
 
71
- defineAspects(EstimatedDocumentCountOperation, [Aspect.READ_OPERATION, Aspect.RETRYABLE]);
71
+ defineAspects(EstimatedDocumentCountOperation, [
72
+ Aspect.READ_OPERATION,
73
+ Aspect.RETRYABLE,
74
+ Aspect.CURSOR_CREATING
75
+ ]);
@@ -43,7 +43,7 @@ export class EvalOperation extends CommandOperation<Document> {
43
43
  let finalParameters: Document[] = [];
44
44
 
45
45
  // If not a code object translate to one
46
- if (!(finalCode && ((finalCode as unknown) as { _bsontype: string })._bsontype === 'Code')) {
46
+ if (!(finalCode && (finalCode as unknown as { _bsontype: string })._bsontype === 'Code')) {
47
47
  finalCode = new Code(finalCode as never);
48
48
  }
49
49
 
@@ -3,16 +3,20 @@ import {
3
3
  MongoError,
4
4
  isRetryableError,
5
5
  MONGODB_ERROR_CODES,
6
- MongoDriverError,
7
- MongoServerError
6
+ MongoRuntimeError,
7
+ MongoNetworkError,
8
+ MongoCompatibilityError,
9
+ MongoServerError,
10
+ MongoExpiredSessionError,
11
+ MongoTransactionError
8
12
  } from '../error';
9
13
  import { Aspect, AbstractOperation } from './operation';
10
14
  import { maxWireVersion, maybePromise, Callback } from '../utils';
11
- import { ServerType } from '../sdam/common';
12
15
  import type { Server } from '../sdam/server';
13
16
  import type { Topology } from '../sdam/topology';
14
17
  import type { ClientSession } from '../sessions';
15
18
  import type { Document } from '../bson';
19
+ import { supportsRetryableWrites } from '../utils';
16
20
 
17
21
  const MMAPv1_RETRY_WRITES_ERROR_CODE = MONGODB_ERROR_CODES.IllegalOperation;
18
22
  const MMAPv1_RETRY_WRITES_ERROR_MESSAGE =
@@ -64,7 +68,8 @@ export function executeOperation<
64
68
  TResult = ResultTypeFromOperation<T>
65
69
  >(topology: Topology, operation: T, callback?: Callback<TResult>): Promise<TResult> | void {
66
70
  if (!(operation instanceof AbstractOperation)) {
67
- throw new MongoDriverError('This method requires a valid operation instance');
71
+ // TODO(NODE-3483)
72
+ throw new MongoRuntimeError('This method requires a valid operation instance');
68
73
  }
69
74
 
70
75
  return maybePromise(callback, cb => {
@@ -85,14 +90,14 @@ export function executeOperation<
85
90
  owner = Symbol();
86
91
  session = topology.startSession({ owner, explicit: false });
87
92
  } else if (session.hasEnded) {
88
- return cb(new MongoDriverError('Use of expired sessions is not permitted'));
93
+ return cb(new MongoExpiredSessionError('Use of expired sessions is not permitted'));
89
94
  } else if (session.snapshotEnabled && !topology.capabilities.supportsSnapshotReads) {
90
- return cb(new MongoDriverError('Snapshot reads require MongoDB 5.0 or later'));
95
+ return cb(new MongoCompatibilityError('Snapshot reads require MongoDB 5.0 or later'));
91
96
  }
92
97
  } else if (session) {
93
98
  // If the user passed an explicit session and we are still, after server selection,
94
99
  // trying to run against a topology that doesn't support sessions we error out.
95
- return cb(new MongoDriverError('Current topology does not support sessions'));
100
+ return cb(new MongoCompatibilityError('Current topology does not support sessions'));
96
101
  }
97
102
 
98
103
  try {
@@ -128,7 +133,7 @@ function executeWithServerSelection(
128
133
 
129
134
  if (inTransaction && !readPreference.equals(ReadPreference.primary)) {
130
135
  callback(
131
- new MongoDriverError(
136
+ new MongoTransactionError(
132
137
  `Read preference in a transaction must be primary, not: ${readPreference.mode}`
133
138
  )
134
139
  );
@@ -136,6 +141,15 @@ function executeWithServerSelection(
136
141
  return;
137
142
  }
138
143
 
144
+ if (
145
+ session &&
146
+ session.isPinned &&
147
+ session.transaction.isCommitted &&
148
+ !operation.bypassPinningCheck
149
+ ) {
150
+ session.unpin();
151
+ }
152
+
139
153
  const serverSelectionOptions = { session };
140
154
  function callbackWithRetry(err?: any, result?: any) {
141
155
  if (err == null) {
@@ -168,16 +182,31 @@ function executeWithServerSelection(
168
182
  }
169
183
 
170
184
  // select a new server, and attempt to retry the operation
171
- topology.selectServer(readPreference, serverSelectionOptions, (err?: any, server?: any) => {
185
+ topology.selectServer(readPreference, serverSelectionOptions, (e?: any, server?: any) => {
172
186
  if (
173
- err ||
187
+ e ||
174
188
  (operation.hasAspect(Aspect.READ_OPERATION) && !supportsRetryableReads(server)) ||
175
189
  (operation.hasAspect(Aspect.WRITE_OPERATION) && !supportsRetryableWrites(server))
176
190
  ) {
177
- callback(err);
191
+ callback(e);
178
192
  return;
179
193
  }
180
194
 
195
+ // If we have a cursor and the initial command fails with a network error,
196
+ // we can retry it on another connection. So we need to check it back in, clear the
197
+ // pool for the service id, and retry again.
198
+ if (
199
+ err &&
200
+ err instanceof MongoNetworkError &&
201
+ server.loadBalanced &&
202
+ session &&
203
+ session.isPinned &&
204
+ !session.inTransaction() &&
205
+ operation.hasAspect(Aspect.CURSOR_CREATING)
206
+ ) {
207
+ session.unpin({ force: true, forceClear: true });
208
+ }
209
+
181
210
  operation.execute(server, session, callback);
182
211
  });
183
212
  }
@@ -189,7 +218,7 @@ function executeWithServerSelection(
189
218
  session.inTransaction()
190
219
  ) {
191
220
  callback(
192
- new MongoDriverError(
221
+ new MongoTransactionError(
193
222
  `Read preference in a transaction must be primary, not: ${readPreference.mode}`
194
223
  )
195
224
  );
@@ -238,11 +267,3 @@ function executeWithServerSelection(
238
267
  function shouldRetryWrite(err: any) {
239
268
  return err instanceof MongoError && err.hasErrorLabel('RetryableWriteError');
240
269
  }
241
-
242
- function supportsRetryableWrites(server: Server) {
243
- return (
244
- server.description.maxWireVersion >= 6 &&
245
- server.description.logicalSessionTimeoutMinutes &&
246
- server.description.type !== ServerType.Standalone
247
- );
248
- }
@@ -6,7 +6,7 @@ import {
6
6
  normalizeHintField,
7
7
  decorateWithExplain
8
8
  } from '../utils';
9
- import { MongoDriverError } from '../error';
9
+ import { MongoInvalidArgumentError, MongoCompatibilityError } from '../error';
10
10
  import type { Document } from '../bson';
11
11
  import type { Server } from '../sdam/server';
12
12
  import type { Collection } from '../collection';
@@ -15,16 +15,19 @@ import { Sort, formatSort } from '../sort';
15
15
  import { isSharded } from '../cmap/wire_protocol/shared';
16
16
  import { ReadConcern } from '../read_concern';
17
17
  import type { ClientSession } from '../sessions';
18
- import type { Projection } from '../mongo_types';
19
18
 
20
- /** @public */
21
- export interface FindOptions<TSchema = Document> extends CommandOperationOptions {
19
+ /**
20
+ * @public
21
+ * @typeParam TSchema - Unused schema definition, deprecated usage, only specify `FindOptions` with no generic
22
+ */
23
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
24
+ export interface FindOptions<TSchema extends Document = Document> extends CommandOperationOptions {
22
25
  /** Sets the limit of documents returned in the query. */
23
26
  limit?: number;
24
27
  /** Set to sort the documents coming back from the query. Array of indexes, `[['a', 1]]` etc. */
25
28
  sort?: Sort;
26
29
  /** The fields to return in the query. Object of fields to either include or exclude (one of, not both), `{'a':1, 'b': 1}` **or** `{'a': 0, 'b': 0}` */
27
- projection?: Projection<TSchema>;
30
+ projection?: Document;
28
31
  /** Set to skip N documents ahead in your query (useful for pagination). */
29
32
  skip?: number;
30
33
  /** Tell the query to use specific indexes in the query. Object of indexes to use, `{'_id':1}` */
@@ -84,15 +87,15 @@ export class FindOperation extends CommandOperation<Document> {
84
87
  this.ns = ns;
85
88
 
86
89
  if (typeof filter !== 'object' || Array.isArray(filter)) {
87
- throw new MongoDriverError('Query filter must be a plain object or ObjectId');
90
+ throw new MongoInvalidArgumentError('Query filter must be a plain object or ObjectId');
88
91
  }
89
92
 
90
93
  // If the filter is a buffer, validate that is a valid BSON document
91
94
  if (Buffer.isBuffer(filter)) {
92
95
  const objectSize = filter[0] | (filter[1] << 8) | (filter[2] << 16) | (filter[3] << 24);
93
96
  if (objectSize !== filter.length) {
94
- throw new MongoDriverError(
95
- `query filter raw message size does not match message header size [${filter.length}] != [${objectSize}]`
97
+ throw new MongoInvalidArgumentError(
98
+ `Query filter raw message size does not match message header size [${filter.length}] != [${objectSize}]`
96
99
  );
97
100
  }
98
101
  }
@@ -106,14 +109,16 @@ export class FindOperation extends CommandOperation<Document> {
106
109
 
107
110
  const serverWireVersion = maxWireVersion(server);
108
111
  const options = this.options;
109
- if (typeof options.allowDiskUse !== 'undefined' && serverWireVersion < 4) {
110
- callback(new MongoDriverError('The `allowDiskUse` option is not supported on MongoDB < 3.2'));
112
+ if (options.allowDiskUse != null && serverWireVersion < 4) {
113
+ callback(
114
+ new MongoCompatibilityError('Option "allowDiskUse" is not supported on MongoDB < 3.2')
115
+ );
111
116
  return;
112
117
  }
113
118
 
114
119
  if (options.collation && serverWireVersion < SUPPORTS_WRITE_CONCERN_AND_COLLATION) {
115
120
  callback(
116
- new MongoDriverError(
121
+ new MongoCompatibilityError(
117
122
  `Server ${server.name}, which reports wire version ${serverWireVersion}, does not support collation`
118
123
  )
119
124
  );
@@ -124,8 +129,8 @@ export class FindOperation extends CommandOperation<Document> {
124
129
  if (serverWireVersion < 4) {
125
130
  if (this.readConcern && this.readConcern.level !== 'local') {
126
131
  callback(
127
- new MongoDriverError(
128
- `server find command does not support a readConcern level of ${this.readConcern.level}`
132
+ new MongoCompatibilityError(
133
+ `Server find command does not support a readConcern level of ${this.readConcern.level}`
129
134
  )
130
135
  );
131
136
 
@@ -161,7 +166,6 @@ export class FindOperation extends CommandOperation<Document> {
161
166
  this.ns,
162
167
  findCommand,
163
168
  {
164
- fullResult: !!this.fullResponse,
165
169
  ...this.options,
166
170
  ...this.bsonOptions,
167
171
  documentsReturnedIn: 'firstBatch',
@@ -336,11 +340,16 @@ function makeLegacyFindCommand(
336
340
  findCommand.$maxTimeMS = options.maxTimeMS;
337
341
  }
338
342
 
339
- if (typeof options.explain !== 'undefined') {
343
+ if (options.explain != null) {
340
344
  findCommand.$explain = true;
341
345
  }
342
346
 
343
347
  return findCommand;
344
348
  }
345
349
 
346
- defineAspects(FindOperation, [Aspect.READ_OPERATION, Aspect.RETRYABLE, Aspect.EXPLAINABLE]);
350
+ defineAspects(FindOperation, [
351
+ Aspect.READ_OPERATION,
352
+ Aspect.RETRYABLE,
353
+ Aspect.EXPLAINABLE,
354
+ Aspect.CURSOR_CREATING
355
+ ]);