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
@@ -1,5 +1,10 @@
1
1
  import { Readable } from 'stream';
2
- import { AnyError, MongoDriverError } from '../error';
2
+ import {
3
+ MongoRuntimeError,
4
+ MongoGridFSChunkError,
5
+ MongoGridFSStreamError,
6
+ MongoInvalidArgumentError
7
+ } from '../error';
3
8
  import type { Document } from '../bson';
4
9
  import type { FindOptions } from '../operations/find';
5
10
  import type { Sort } from '../sort';
@@ -68,7 +73,7 @@ export interface GridFSBucketReadStreamPrivate {
68
73
  * Do not instantiate this class directly. Use `openDownloadStream()` instead.
69
74
  * @public
70
75
  */
71
- export class GridFSBucketReadStream extends Readable {
76
+ export class GridFSBucketReadStream extends Readable implements NodeJS.ReadableStream {
72
77
  /** @internal */
73
78
  s: GridFSBucketReadStreamPrivate;
74
79
 
@@ -195,7 +200,7 @@ export class GridFSBucketReadStream extends Readable {
195
200
 
196
201
  function throwIfInitialized(stream: GridFSBucketReadStream): void {
197
202
  if (stream.s.init) {
198
- throw new MongoDriverError('Options cannot be changed after the stream is initialized');
203
+ throw new MongoGridFSStreamError('Options cannot be changed after the stream is initialized');
199
204
  }
200
205
  }
201
206
 
@@ -209,7 +214,8 @@ function doRead(stream: GridFSBucketReadStream): void {
209
214
  return;
210
215
  }
211
216
  if (error) {
212
- return __handleError(stream, error);
217
+ stream.emit(GridFSBucketReadStream.ERROR, error);
218
+ return;
213
219
  }
214
220
  if (!doc) {
215
221
  stream.push(null);
@@ -218,7 +224,7 @@ function doRead(stream: GridFSBucketReadStream): void {
218
224
  if (!stream.s.cursor) return;
219
225
  stream.s.cursor.close(error => {
220
226
  if (error) {
221
- __handleError(stream, error);
227
+ stream.emit(GridFSBucketReadStream.ERROR, error);
222
228
  return;
223
229
  }
224
230
 
@@ -234,31 +240,38 @@ function doRead(stream: GridFSBucketReadStream): void {
234
240
  const bytesRemaining = stream.s.file.length - stream.s.bytesRead;
235
241
  const expectedN = stream.s.expected++;
236
242
  const expectedLength = Math.min(stream.s.file.chunkSize, bytesRemaining);
237
- let errmsg: string;
238
243
  if (doc.n > expectedN) {
239
- errmsg = 'ChunkIsMissing: Got unexpected n: ' + doc.n + ', expected: ' + expectedN;
240
- return __handleError(stream, new MongoDriverError(errmsg));
244
+ return stream.emit(
245
+ GridFSBucketReadStream.ERROR,
246
+ new MongoGridFSChunkError(
247
+ `ChunkIsMissing: Got unexpected n: ${doc.n}, expected: ${expectedN}`
248
+ )
249
+ );
241
250
  }
242
251
 
243
252
  if (doc.n < expectedN) {
244
- errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n + ', expected: ' + expectedN;
245
- return __handleError(stream, new MongoDriverError(errmsg));
253
+ return stream.emit(
254
+ GridFSBucketReadStream.ERROR,
255
+ new MongoGridFSChunkError(`ExtraChunk: Got unexpected n: ${doc.n}, expected: ${expectedN}`)
256
+ );
246
257
  }
247
258
 
248
259
  let buf = Buffer.isBuffer(doc.data) ? doc.data : doc.data.buffer;
249
260
 
250
261
  if (buf.byteLength !== expectedLength) {
251
262
  if (bytesRemaining <= 0) {
252
- errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n;
253
- return __handleError(stream, new MongoDriverError(errmsg));
263
+ return stream.emit(
264
+ GridFSBucketReadStream.ERROR,
265
+ new MongoGridFSChunkError(`ExtraChunk: Got unexpected n: ${doc.n}`)
266
+ );
254
267
  }
255
268
 
256
- errmsg =
257
- 'ChunkIsWrongSize: Got unexpected length: ' +
258
- buf.byteLength +
259
- ', expected: ' +
260
- expectedLength;
261
- return __handleError(stream, new MongoDriverError(errmsg));
269
+ return stream.emit(
270
+ GridFSBucketReadStream.ERROR,
271
+ new MongoGridFSChunkError(
272
+ `ChunkIsWrongSize: Got unexpected length: ${buf.byteLength}, expected: ${expectedLength}`
273
+ )
274
+ );
262
275
  }
263
276
 
264
277
  stream.s.bytesRead += buf.byteLength;
@@ -305,17 +318,18 @@ function init(stream: GridFSBucketReadStream): void {
305
318
 
306
319
  stream.s.files.findOne(stream.s.filter, findOneOptions, (error, doc) => {
307
320
  if (error) {
308
- return __handleError(stream, error);
321
+ return stream.emit(GridFSBucketReadStream.ERROR, error);
309
322
  }
310
323
 
311
324
  if (!doc) {
312
325
  const identifier = stream.s.filter._id
313
326
  ? stream.s.filter._id.toString()
314
327
  : stream.s.filter.filename;
315
- const errmsg = 'FileNotFound: file ' + identifier + ' was not found';
316
- const err = new MongoDriverError(errmsg);
328
+ const errmsg = `FileNotFound: file ${identifier} was not found`;
329
+ // TODO(NODE-3483)
330
+ const err = new MongoRuntimeError(errmsg);
317
331
  err.code = 'ENOENT'; // TODO: NODE-3338 set property as part of constructor
318
- return __handleError(stream, err);
332
+ return stream.emit(GridFSBucketReadStream.ERROR, err);
319
333
  }
320
334
 
321
335
  // If document is empty, kill the stream immediately and don't
@@ -336,7 +350,7 @@ function init(stream: GridFSBucketReadStream): void {
336
350
  try {
337
351
  stream.s.bytesToSkip = handleStartOption(stream, doc, stream.s.options);
338
352
  } catch (error) {
339
- return __handleError(stream, error);
353
+ return stream.emit(GridFSBucketReadStream.ERROR, error);
340
354
  }
341
355
 
342
356
  const filter: Document = { files_id: doc._id };
@@ -362,7 +376,7 @@ function init(stream: GridFSBucketReadStream): void {
362
376
  try {
363
377
  stream.s.bytesToTrim = handleEndOption(stream, doc, stream.s.cursor, stream.s.options);
364
378
  } catch (error) {
365
- return __handleError(stream, error);
379
+ return stream.emit(GridFSBucketReadStream.ERROR, error);
366
380
  }
367
381
 
368
382
  stream.emit(GridFSBucketReadStream.FILE, doc);
@@ -391,26 +405,16 @@ function handleStartOption(
391
405
  ): number {
392
406
  if (options && options.start != null) {
393
407
  if (options.start > doc.length) {
394
- throw new MongoDriverError(
395
- 'Stream start (' +
396
- options.start +
397
- ') must not be ' +
398
- 'more than the length of the file (' +
399
- doc.length +
400
- ')'
408
+ throw new MongoInvalidArgumentError(
409
+ `Stream start (${options.start}) must not be more than the length of the file (${doc.length})`
401
410
  );
402
411
  }
403
412
  if (options.start < 0) {
404
- throw new MongoDriverError('Stream start (' + options.start + ') must not be ' + 'negative');
413
+ throw new MongoInvalidArgumentError(`Stream start (${options.start}) must not be negative`);
405
414
  }
406
415
  if (options.end != null && options.end < options.start) {
407
- throw new MongoDriverError(
408
- 'Stream start (' +
409
- options.start +
410
- ') must not be ' +
411
- 'greater than stream end (' +
412
- options.end +
413
- ')'
416
+ throw new MongoInvalidArgumentError(
417
+ `Stream start (${options.start}) must not be greater than stream end (${options.end})`
414
418
  );
415
419
  }
416
420
 
@@ -419,7 +423,7 @@ function handleStartOption(
419
423
 
420
424
  return options.start - stream.s.bytesRead;
421
425
  }
422
- throw new MongoDriverError('No start option defined');
426
+ throw new MongoInvalidArgumentError('Start option must be defined');
423
427
  }
424
428
 
425
429
  function handleEndOption(
@@ -430,17 +434,12 @@ function handleEndOption(
430
434
  ) {
431
435
  if (options && options.end != null) {
432
436
  if (options.end > doc.length) {
433
- throw new MongoDriverError(
434
- 'Stream end (' +
435
- options.end +
436
- ') must not be ' +
437
- 'more than the length of the file (' +
438
- doc.length +
439
- ')'
437
+ throw new MongoInvalidArgumentError(
438
+ `Stream end (${options.end}) must not be more than the length of the file (${doc.length})`
440
439
  );
441
440
  }
442
441
  if (options.start == null || options.start < 0) {
443
- throw new MongoDriverError('Stream end (' + options.end + ') must not be ' + 'negative');
442
+ throw new MongoInvalidArgumentError(`Stream end (${options.end}) must not be negative`);
444
443
  }
445
444
 
446
445
  const start = options.start != null ? Math.floor(options.start / doc.chunkSize) : 0;
@@ -451,9 +450,5 @@ function handleEndOption(
451
450
 
452
451
  return Math.ceil(options.end / doc.chunkSize) * doc.chunkSize - options.end;
453
452
  }
454
- throw new MongoDriverError('No end option defined');
455
- }
456
-
457
- function __handleError(stream: GridFSBucketReadStream, error?: AnyError): void {
458
- stream.emit(GridFSBucketReadStream.ERROR, error);
453
+ throw new MongoInvalidArgumentError('End option must be defined');
459
454
  }
@@ -1,4 +1,4 @@
1
- import { MongoDriverError } from '../error';
1
+ import { MongoRuntimeError } from '../error';
2
2
  import {
3
3
  GridFSBucketReadStream,
4
4
  GridFSBucketReadStreamOptions,
@@ -227,8 +227,9 @@ function _delete(bucket: GridFSBucket, id: ObjectId, callback: Callback<void>):
227
227
 
228
228
  // Delete orphaned chunks before returning FileNotFound
229
229
  if (!res?.deletedCount) {
230
- const errmsg = 'FileNotFound: no file with id ' + id + ' found';
231
- return callback(new MongoDriverError(errmsg));
230
+ // TODO(NODE-3483): Replace with more appropriate error
231
+ // Consider creating new error MongoGridFSFileNotFoundError
232
+ return callback(new MongoRuntimeError(`File not found for id ${id}`));
232
233
  }
233
234
 
234
235
  return callback();
@@ -250,7 +251,7 @@ function _rename(
250
251
  }
251
252
 
252
253
  if (!res?.matchedCount) {
253
- return callback(new MongoDriverError(`File with id ${id} not found`));
254
+ return callback(new MongoRuntimeError(`File with id ${id} not found`));
254
255
  }
255
256
 
256
257
  return callback();
@@ -1,14 +1,13 @@
1
1
  import { Writable } from 'stream';
2
- import { MongoError, AnyError, MONGODB_ERROR_CODES, MongoDriverError } from '../error';
3
- import { WriteConcern } from './../write_concern';
4
- import { PromiseProvider } from '../promise_provider';
5
- import { ObjectId } from '../bson';
6
- import type { Callback } from '../utils';
7
2
  import type { Document } from '../bson';
8
- import type { GridFSBucket } from './index';
9
- import type { GridFSFile } from './download';
10
- import type { WriteConcernOptions } from '../write_concern';
3
+ import { ObjectId } from '../bson';
11
4
  import type { Collection } from '../collection';
5
+ import { AnyError, MONGODB_ERROR_CODES, MongoError, MongoAPIError } from '../error';
6
+ import { Callback, maybePromise } from '../utils';
7
+ import type { WriteConcernOptions } from '../write_concern';
8
+ import { WriteConcern } from './../write_concern';
9
+ import type { GridFSFile } from './download';
10
+ import type { GridFSBucket } from './index';
12
11
 
13
12
  /** @public */
14
13
  export interface GridFSChunk {
@@ -38,7 +37,7 @@ export interface GridFSBucketWriteStreamOptions extends WriteConcernOptions {
38
37
  * Do not instantiate this class directly. Use `openUploadStream()` instead.
39
38
  * @public
40
39
  */
41
- export class GridFSBucketWriteStream extends Writable {
40
+ export class GridFSBucketWriteStream extends Writable implements NodeJS.WritableStream {
42
41
  bucket: GridFSBucket;
43
42
  chunks: Collection<GridFSChunk>;
44
43
  filename: string;
@@ -119,12 +118,16 @@ export class GridFSBucketWriteStream extends Writable {
119
118
  * @param callback - Function to call when the chunk was added to the buffer, or if the entire chunk was persisted to MongoDB if this chunk caused a flush.
120
119
  * @returns False if this write required flushing a chunk to MongoDB. True otherwise.
121
120
  */
122
- write(chunk: Buffer): boolean;
123
- write(chunk: Buffer, callback: Callback<void>): boolean;
124
- write(chunk: Buffer, encoding: BufferEncoding | undefined): boolean;
125
- write(chunk: Buffer, encoding: BufferEncoding | undefined, callback: Callback<void>): boolean;
121
+ write(chunk: Buffer | string): boolean;
122
+ write(chunk: Buffer | string, callback: Callback<void>): boolean;
123
+ write(chunk: Buffer | string, encoding: BufferEncoding | undefined): boolean;
126
124
  write(
127
- chunk: Buffer,
125
+ chunk: Buffer | string,
126
+ encoding: BufferEncoding | undefined,
127
+ callback: Callback<void>
128
+ ): boolean;
129
+ write(
130
+ chunk: Buffer | string,
128
131
  encodingOrCallback?: Callback<void> | BufferEncoding,
129
132
  callback?: Callback<void>
130
133
  ): boolean {
@@ -133,6 +136,7 @@ export class GridFSBucketWriteStream extends Writable {
133
136
  return waitForIndexes(this, () => doWrite(this, chunk, encoding, callback));
134
137
  }
135
138
 
139
+ // TODO(NODE-3405): Refactor this with maybePromise and MongoStreamClosedError
136
140
  /**
137
141
  * Places this write stream into an aborted state (all future writes fail)
138
142
  * and deletes all chunks that have already been written.
@@ -142,25 +146,19 @@ export class GridFSBucketWriteStream extends Writable {
142
146
  abort(): Promise<void>;
143
147
  abort(callback: Callback<void>): void;
144
148
  abort(callback?: Callback<void>): Promise<void> | void {
145
- const Promise = PromiseProvider.get();
146
- let error: MongoDriverError;
147
- if (this.state.streamEnd) {
148
- error = new MongoDriverError('Cannot abort a stream that has already completed');
149
- if (typeof callback === 'function') {
150
- return callback(error);
149
+ return maybePromise(callback, callback => {
150
+ if (this.state.streamEnd) {
151
+ // TODO(NODE-3485): Replace with MongoGridFSStreamClosed
152
+ return callback(new MongoAPIError('Cannot abort a stream that has already completed'));
151
153
  }
152
- return Promise.reject(error);
153
- }
154
- if (this.state.aborted) {
155
- error = new MongoDriverError('Cannot call abort() on a stream twice');
156
- if (typeof callback === 'function') {
157
- return callback(error);
154
+
155
+ if (this.state.aborted) {
156
+ // TODO(NODE-3485): Replace with MongoGridFSStreamClosed
157
+ return callback(new MongoAPIError('Cannot call abort() on a stream twice'));
158
158
  }
159
- return Promise.reject(error);
160
- }
161
- this.state.aborted = true;
162
- this.chunks.deleteMany({ files_id: this.id }, error => {
163
- if (typeof callback === 'function') callback(error);
159
+
160
+ this.state.aborted = true;
161
+ this.chunks.deleteMany({ files_id: this.id }, error => callback(error));
164
162
  });
165
163
  }
166
164
 
@@ -423,7 +421,7 @@ function createFilesDoc(
423
421
 
424
422
  function doWrite(
425
423
  stream: GridFSBucketWriteStream,
426
- chunk: Buffer,
424
+ chunk: Buffer | string,
427
425
  encoding?: BufferEncoding,
428
426
  callback?: Callback<void>
429
427
  ): boolean {
@@ -556,7 +554,8 @@ function writeRemnant(stream: GridFSBucketWriteStream, callback?: Callback): boo
556
554
  function checkAborted(stream: GridFSBucketWriteStream, callback?: Callback<void>): boolean {
557
555
  if (stream.state.aborted) {
558
556
  if (typeof callback === 'function') {
559
- callback(new MongoDriverError('this stream has been aborted'));
557
+ // TODO(NODE-3485): Replace with MongoGridFSStreamClosedError
558
+ callback(new MongoAPIError('Stream has been aborted'));
560
559
  }
561
560
  return true;
562
561
  }
package/src/index.ts CHANGED
@@ -29,16 +29,42 @@ export {
29
29
  Map
30
30
  } from './bson';
31
31
 
32
+ import { ObjectId } from 'bson';
33
+ /**
34
+ * @public
35
+ * @deprecated Please use `ObjectId`
36
+ */
37
+ export const ObjectID = ObjectId;
38
+
32
39
  export {
33
40
  MongoError,
34
41
  MongoServerError,
35
42
  MongoDriverError,
43
+ MongoAPIError,
44
+ MongoCompatibilityError,
45
+ MongoInvalidArgumentError,
46
+ MongoMissingCredentialsError,
47
+ MongoMissingDependencyError,
36
48
  MongoNetworkError,
37
49
  MongoNetworkTimeoutError,
38
50
  MongoSystemError,
39
51
  MongoServerSelectionError,
40
52
  MongoParseError,
41
- MongoWriteConcernError
53
+ MongoWriteConcernError,
54
+ MongoRuntimeError,
55
+ MongoChangeStreamError,
56
+ MongoGridFSStreamError,
57
+ MongoGridFSChunkError,
58
+ MongoDecompressionError,
59
+ MongoBatchReExecutionError,
60
+ MongoCursorExhaustedError,
61
+ MongoCursorInUseError,
62
+ MongoNotConnectedError,
63
+ MongoExpiredSessionError,
64
+ MongoTransactionError,
65
+ MongoKerberosError,
66
+ MongoServerClosedError,
67
+ MongoTopologyClosedError
42
68
  } from './error';
43
69
  export { MongoBulkWriteError, BulkWriteOptions, AnyBulkWriteOperation } from './bulk/common';
44
70
  export {
@@ -141,7 +167,11 @@ export type {
141
167
  OperationTime,
142
168
  ResumeOptions
143
169
  } from './change_stream';
144
- export type { MongoCredentials, MongoCredentialsOptions } from './cmap/auth/mongo_credentials';
170
+ export type {
171
+ MongoCredentials,
172
+ AuthMechanismProperties,
173
+ MongoCredentialsOptions
174
+ } from './cmap/auth/mongo_credentials';
145
175
  export type {
146
176
  WriteProtocolMessageType,
147
177
  Query,
@@ -161,6 +191,7 @@ export type {
161
191
  GetMoreOptions,
162
192
  ConnectionEvents
163
193
  } from './cmap/connection';
194
+ export type { ConnectionPoolMetrics } from './cmap/metrics';
164
195
  export type {
165
196
  CloseOptions,
166
197
  ConnectionPoolOptions,
@@ -187,7 +218,7 @@ export type {
187
218
  } from './cursor/abstract_cursor';
188
219
  export type { DbPrivate, DbOptions } from './db';
189
220
  export type { AutoEncryptionOptions, AutoEncrypter } from './deps';
190
- export type { AnyError, ErrorDescription, MongoNetworkTimeoutErrorOptions } from './error';
221
+ export type { AnyError, ErrorDescription, MongoNetworkErrorOptions } from './error';
191
222
  export type { Explain, ExplainOptions, ExplainVerbosityLike } from './explain';
192
223
  export type {
193
224
  GridFSBucketReadStream,
@@ -334,6 +365,7 @@ export type {
334
365
  ClientSession,
335
366
  ClientSessionEvents,
336
367
  ClientSessionOptions,
368
+ EndSessionOptions,
337
369
  ServerSessionPool,
338
370
  ServerSession,
339
371
  ServerSessionId,
@@ -353,7 +385,13 @@ export type {
353
385
  export type { W, WriteConcernOptions, WriteConcernSettings } from './write_concern';
354
386
  export type { ExecutionResult } from './operations/execute_operation';
355
387
  export type { InternalAbstractCursorOptions } from './cursor/abstract_cursor';
356
- export type { BulkOperationBase, BulkOperationPrivate, FindOperators, Batch } from './bulk/common';
388
+ export type {
389
+ BulkOperationBase,
390
+ BulkOperationPrivate,
391
+ FindOperators,
392
+ Batch,
393
+ WriteConcernErrorData
394
+ } from './bulk/common';
357
395
  export type { OrderedBulkOperation } from './bulk/ordered';
358
396
  export type { UnorderedBulkOperation } from './bulk/unordered';
359
397
  export type { Encrypter, EncrypterOptions } from './encrypter';
package/src/logger.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { format } from 'util';
2
- import { MongoDriverError } from './error';
2
+ import { enumToString } from './utils';
3
+ import { MongoInvalidArgumentError } from './error';
3
4
 
4
5
  // Filters for classes
5
6
  const classFilters: any = {};
@@ -222,7 +223,7 @@ export class Logger {
222
223
  */
223
224
  static setCurrentLogger(logger: LoggerFunction): void {
224
225
  if (typeof logger !== 'function') {
225
- throw new MongoDriverError('current logger must be a function');
226
+ throw new MongoInvalidArgumentError('Current logger must be a function');
226
227
  }
227
228
 
228
229
  currentLogger = logger;
@@ -253,7 +254,9 @@ export class Logger {
253
254
  newLevel !== LoggerLevel.DEBUG &&
254
255
  newLevel !== LoggerLevel.WARN
255
256
  ) {
256
- throw new MongoDriverError(`${newLevel} is an illegal logging level`);
257
+ throw new MongoInvalidArgumentError(
258
+ `Argument "newLevel" should be one of ${enumToString(LoggerLevel)}`
259
+ );
257
260
  }
258
261
 
259
262
  level = newLevel;
@@ -1,7 +1,12 @@
1
1
  import { Db, DbOptions } from './db';
2
2
  import { ChangeStream, ChangeStreamOptions } from './change_stream';
3
3
  import type { ReadPreference, ReadPreferenceMode } from './read_preference';
4
- import { AnyError, MongoDriverError } from './error';
4
+ import {
5
+ AnyError,
6
+ MongoRuntimeError,
7
+ MongoInvalidArgumentError,
8
+ MongoNotConnectedError
9
+ } from './error';
5
10
  import type { W, WriteConcern } from './write_concern';
6
11
  import {
7
12
  maybePromise,
@@ -22,7 +27,7 @@ import type { AuthMechanism } from './cmap/auth/defaultAuthProviders';
22
27
  import type { Topology, TopologyEvents } from './sdam/topology';
23
28
  import type { ClientSession, ClientSessionOptions } from './sessions';
24
29
  import type { TagSet } from './sdam/server_description';
25
- import type { MongoCredentials } from './cmap/auth/mongo_credentials';
30
+ import type { AuthMechanismProperties, MongoCredentials } from './cmap/auth/mongo_credentials';
26
31
  import { parseOptions } from './connection_string';
27
32
  import type { CompressorName } from './cmap/wire_protocol/compression';
28
33
  import type { TLSSocketOptions, ConnectionOptions as TLSConnectionOptions } from 'tls';
@@ -107,7 +112,7 @@ export interface MongoClientOptions extends BSONSerializeOptions, SupportedNodeC
107
112
  ssl?: boolean;
108
113
  /** Specifies the location of a local TLS Certificate */
109
114
  tlsCertificateFile?: string;
110
- /** Specifies the location of a local .pem file that contains either the clients TLS/SSL certificate or the clients TLS/SSL certificate and key. */
115
+ /** Specifies the location of a local .pem file that contains either the client's TLS/SSL certificate and key or only the client's TLS/SSL key when tlsCertificateFile is used to provide the certificate. */
111
116
  tlsCertificateKeyFile?: string;
112
117
  /** Specifies the password to de-crypt the tlsCertificateKeyFile. */
113
118
  tlsCertificateKeyFilePassword?: string;
@@ -123,8 +128,8 @@ export interface MongoClientOptions extends BSONSerializeOptions, SupportedNodeC
123
128
  connectTimeoutMS?: number;
124
129
  /** The time in milliseconds to attempt a send or receive on a socket before the attempt times out. */
125
130
  socketTimeoutMS?: number;
126
- /** Comma-delimited string of compressors to enable network compression for communication between this client and a mongod/mongos instance. */
127
- compressors?: CompressorName[];
131
+ /** An array or comma-delimited string of compressors to enable network compression for communication between this client and a mongod/mongos instance. */
132
+ compressors?: CompressorName[] | string;
128
133
  /** An integer that specifies the compression level if using zlib for network compression. */
129
134
  zlibCompressionLevel?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | undefined;
130
135
  /** The maximum number of connections in the connection pool. */
@@ -152,12 +157,7 @@ export interface MongoClientOptions extends BSONSerializeOptions, SupportedNodeC
152
157
  /** Specify the authentication mechanism that MongoDB will use to authenticate the connection. */
153
158
  authMechanism?: AuthMechanism;
154
159
  /** Specify properties for the specified authMechanism as a comma-separated list of colon-separated key-value pairs. */
155
- authMechanismProperties?: {
156
- SERVICE_NAME?: string;
157
- CANONICALIZE_HOST_NAME?: boolean;
158
- SERVICE_REALM?: string;
159
- [key: string]: any;
160
- };
160
+ authMechanismProperties?: AuthMechanismProperties;
161
161
  /** The size (in milliseconds) of the latency window for selecting among multiple suitable MongoDB instances. */
162
162
  localThresholdMS?: number;
163
163
  /** Specifies how long (in milliseconds) to block for server selection before throwing an exception. */
@@ -174,6 +174,8 @@ export interface MongoClientOptions extends BSONSerializeOptions, SupportedNodeC
174
174
  retryWrites?: boolean;
175
175
  /** Allow a driver to force a Single topology type with a connection string containing one host */
176
176
  directConnection?: boolean;
177
+ /** Instruct the driver it is connecting to a load balancer fronting a mongos like service */
178
+ loadBalanced?: boolean;
177
179
 
178
180
  /** The write concern w value */
179
181
  w?: W;
@@ -403,7 +405,7 @@ export class MongoClient extends TypedEventEmitter<MongoClientEvents> {
403
405
  connect(callback: Callback<MongoClient>): void;
404
406
  connect(callback?: Callback<MongoClient>): Promise<MongoClient> | void {
405
407
  if (callback && typeof callback !== 'function') {
406
- throw new MongoDriverError('`connect` only accepts a callback');
408
+ throw new MongoInvalidArgumentError('Method `connect` only accepts a callback');
407
409
  }
408
410
 
409
411
  return maybePromise(callback, cb => {
@@ -473,13 +475,6 @@ export class MongoClient extends TypedEventEmitter<MongoClientEvents> {
473
475
  // Copy the options and add out internal override of the not shared flag
474
476
  const finalOptions = Object.assign({}, this[kOptions], options);
475
477
 
476
- // If no topology throw an error message
477
- if (!this.topology) {
478
- throw new MongoDriverError(
479
- 'MongoClient must be connected before calling MongoClient.prototype.db'
480
- );
481
- }
482
-
483
478
  // Return the db object
484
479
  const db = new Db(this, dbName, finalOptions);
485
480
 
@@ -528,7 +523,7 @@ export class MongoClient extends TypedEventEmitter<MongoClientEvents> {
528
523
  startSession(options?: ClientSessionOptions): ClientSession {
529
524
  options = Object.assign({ explicit: true }, options);
530
525
  if (!this.topology) {
531
- throw new MongoDriverError('Must connect to a server before calling this method');
526
+ throw new MongoNotConnectedError('MongoClient must be connected to start a session');
532
527
  }
533
528
 
534
529
  return this.topology.startSession(options, this.s.options);
@@ -556,7 +551,7 @@ export class MongoClient extends TypedEventEmitter<MongoClientEvents> {
556
551
  }
557
552
 
558
553
  if (callback == null) {
559
- throw new MongoDriverError('Missing required callback parameter');
554
+ throw new MongoInvalidArgumentError('Missing required callback parameter');
560
555
  }
561
556
 
562
557
  const session = this.startSession(options);
@@ -565,7 +560,8 @@ export class MongoClient extends TypedEventEmitter<MongoClientEvents> {
565
560
  let cleanupHandler: CleanUpHandlerFunction = ((err, result, opts) => {
566
561
  // prevent multiple calls to cleanupHandler
567
562
  cleanupHandler = () => {
568
- throw new MongoDriverError('cleanupHandler was called too many times');
563
+ // TODO(NODE-3483)
564
+ throw new MongoRuntimeError('cleanupHandler was called too many times');
569
565
  };
570
566
 
571
567
  opts = Object.assign({ throw: true }, opts);
@@ -624,7 +620,6 @@ export interface MongoOptions
624
620
  Pick<
625
621
  MongoClientOptions,
626
622
  | 'autoEncryption'
627
- | 'compressors'
628
623
  | 'connectTimeoutMS'
629
624
  | 'directConnection'
630
625
  | 'driverInfo'
@@ -661,7 +656,9 @@ export interface MongoOptions
661
656
  credentials?: MongoCredentials;
662
657
  readPreference: ReadPreference;
663
658
  readConcern: ReadConcern;
659
+ loadBalanced: boolean;
664
660
  serverApi: ServerApi;
661
+ compressors: CompressorName[];
665
662
  writeConcern: WriteConcern;
666
663
  dbName: string;
667
664
  metadata: ClientMetadata;