Releases: mongodb/node-mongodb-native
v7.0.0
7.0.0 (2025-11-06)
The MongoDB Node.js team is pleased to announce version 7.0.0 of the mongodb package!
Release Notes
The following is a detailed collection of the changes in the major v7 release of the mongodb package for Node.js.
The main focus of this release was usability improvements and a streamlined API. Read on for details!
Important
This is a list of changes relative to v6.21.0 of the driver. ALL changes listed below are BREAKING unless indicated otherwise.
Users migrating from an older version of the driver are advised to upgrade to at least v6.21.0 before adopting v7.
🛠️ Runtime and dependency updates
Minimum Node.js version is now v20.19.0
The minimum supported Node.js version is now v20.19.0 and our TypeScript target has been updated to ES2023. We strive to keep our minimum supported Node.js version in sync with the runtime's release cadence to keep up with the latest security updates and modern language features.
Notably, the driver now offers native support for explicit resource management. Symbol.asyncDispose implementations are available on the MongoClient, ClientSession, ChangeStream and on cursors.
Note
Explicit resource management is considered experimental in the driver and will be until the TC39 explicit resource management proposal is completed.
bson and mongodb-connection-string-url versions 7.0.0
This driver version has been updated to use bson@7.0.0 and mongodb-connection-string-url@7.0.0, which match the driver's Node.js runtime version support. BSON functionality re-exported from the driver is furthermore subject to the changes outlined in the BSON V7 release notes.
Optional peer dependency releases and version bumps
@mongodb-js/zstdoptional peer dependency minimum version raised to7.0.0, dropped support for1.xand2.x(note that@mongodb-js/zstddoes not have3.x-6.xversion releases)kerberosoptional peer dependency minimum version raised to7.0.0, dropped support for2.x(note thatkerberosdoes not have3.x-6.xversion releases)mongodb-client-encryptionoptional peer dependency minimum version raised to7.0.0, dropped support for6.x
Additionally, the driver is now compatible with the following packages:
| Dependency | Previous Range | New Allowed Range |
|---|---|---|
| @aws-sdk/credential-providers | ^3.188.0 | ^3.806.0 |
| gcp-metadata | ^5.2.0 | ^7.0.1 |
| socks | ^2.7.1 | ^2.8.6 |
🔐 AWS authentication
To improve long-term maintainability and ensure compatibility with AWS updates, we’ve standardized AWS auth to use the official SDK in all cases and made a number of supporting changes outlined below.
@aws-sdk/credential-providers is now required for MONGODB-AWS authentication
Previous versions of the driver contained two implementations for AWS authentication and could run the risk of the custom driver implementation not supporting all AWS authentication features as well as not being correct when AWS makes changes. Using the official AWS SDK in all cases alleviates these issues.
npm install @aws-sdk/credential-providersCustom AWS credential provider takes highest precedence
When providing a custom AWS credential provider via the auth mechanism property AWS_CREDENTIAL_PROVIDER, it will now take the highest precedence over any other AWS auth method.
Explicitly provided credentials no longer accepted with MONGODB-AWS authentication
AWS environments (such as AWS Lambda) do not have credentials that are permanent and expire within a set amount of time. Providing credentials in the URI or options would mandate that those credentials would be valid for the life of the MongoClient, which is problematic. With this change, the fetching of credentials is fully handled by the installed required AWS SDK.
This means that for AWS authentication, all client URIs MUST now be specified as:
import { MongoClient } from 'mongodb';
const client = new MongoClient('mongodb<+srv>://<host>:<port>/?authMechanism=MONGODB-AWS');The previous method of providing URI encoded credentials based on the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY directly in the connection string will no longer work.
⚙️ Error handling improvements
Dropping a collection returns false instead of throwing when NS not found
This change has been made for consistency with the common drivers specifications.
Aggregate with write concern and explain no longer throws client-side
This will now throw a MongoServerError instead.
All encryption-related errors now subclass MongoError
The driver aims to ensure that all errors it throws are subclasses of MongoError. However, when using CSFLE or QE, the driver's encryption implementation could sometimes throw errors that were not instances of MongoError.
Now, all errors thrown during encryption are subclasses of MongoError.
'PoolRequstedRetry' error label renamed to 'PoolRequestedRetry'
The PoolClearedError thrown in cases where the connection pool was cleared now fixes the typo in the error label.
💥 Misc breaking improvements
Change streams no longer filter $changeStream stage options
Users can now pass any option to collection.watch(). If an option is invalid for the $changeStream stage of the pipeline, the server will return an error. This change makes it possible to use newly introduced server options without waiting for them to become available in our public type definitions and eliminates the risk of valid but unrecognized options being silently ignored.
Cursors no longer provide a default batchSize of 1000 for getMores
In driver versions <7.0, the driver provides a default batchSize of 1000 for each getMore when iterating a cursor. This behavior is not ideal because the default is set regardless of the documents being fetched. For example, if a cursor fetches many small documents, the driver's default of 1000 can result in many round-trips to fetch all documents, when the server could fit all documents inside a single getMore if no batchSize were set.
Now, cursors no longer provide a default batchSize when executing a getMore. A batchSize will only be set on getMore commands if a batchSize has been explicitly configured for the cursor.
Auto encryption options now include default filenames in TS
A common source of confusion for people configuring auto encryption is where to specify the path to mongocryptd and where to specify the path to crypt_shared. We've now made this clearer in our Typescript users. Typescript now reports errors if the specified filename doesn't match the default name of the file. Some examples:
var path: AutoEncryptionOptions['extraOptions']['mongocryptdSpawnPath'] = 'some path'; // ERROR
var path: AutoEncryptionOptions['extraOptions']['mongocryptdSpawnPath'] = 'mongocryptd'; // OK
var path: AutoEncryptionOptions['extraOptions']['mongocryptdSpawnPath'] =
'/usr/local/bin/mongocryptd'; // OK
var path: AutoEncryptionOptions['extraOptions']['mongocryptdSpawnPath'] = 'mongocryptd.exe'; // OK
var path: AutoEncryptionOptions['extraOptions']['cryptSharedLibPath'] = 'some path'; // ERROR
var path: AutoEncryptionOptions['extraOptions']['cryptSharedLibPath'] = 'mongo_crypt_v1.so'; // OK
var path: AutoEncryptionOptions['extraOptions']['cryptSharedLibPath'] = 'mongo_crypt_v1.dll'; // OK
var path: AutoEncryptionOptions['extraOptions']['cryptSharedLibPath'] = 'mongo_crypt_v1.dylib'; // OK☀️ Misc non-breaking improvements
Improve MongoClient.connect() consistency across environments
The MongoClient connect function will now run a handshake regardless of credentials being defined. The upshot of this change is that connect is more consistent at verifying some fail-fast preconditions regardless of environment. For example, previously, if connecting to a loadBalanced=true cluster without authentication there would not have been an error until a command was attempted.
MongoClient.close() no longer sends endSessions if the topology does not have session support
MongoClient.close() attempts to free up any server resources that the client has instantiated, including sessions. Previously, MongoClient.close() unconditionally attempted to kill all sessions, regardless of whether or not the topology actually supports sessions.
Now, MongoClient.close() only attempts to clean up sessions if the topology supports sessions.
Wrap socket write in a try/catch to ensure errors can be properly wrapped
One socket.write call was not correctly wrapped in a try/catch block and network errors could bubble up to the driver. This call is now properly wrapped and will result in a retry.
ClientEncryption.rewrapManyDataKey() options now correctly marked as optional
The options parameter for the ClientEncryption.rewrapManyDataKey() method is now correctly marked as optional in its TypeScript definition. This change aligns the type signature with the method's implementation and documentation, resolving a type mismatch for TypeScript users.
📜 Removal of deprecated functionality
Cursor and ChangeStream stream() method no longer accepts a transform
Cursors and ChangeStreams no longer accept a transform function. ReadableStream.map() can be used instead:
// before
const stream = cursor.stream({ transform: JSON.stringify });
// after
cons...v6.21.0
6.21.0 (2025-11-05)
The MongoDB Node.js team is pleased to announce version 6.21.0 of the mongodb package!
Release Notes
Deprecated items to be removed in 7.0.0
The following items have been deprecated and will be removed in 7.0.0:
MongoCredentials.authMechanismProperties.AWS_SESSION_TOKEN // URI & client options for AWS variables will no longer be respected
CommandOptions.noResponse // Unused
ConnectionOptions.cancellationToken // Unused
CursorStreamOptions // Only option, transform, removed in favor of Stream#mapFeatures
Documentation
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
v6.20.0
6.20.0 (2025-09-17)
The MongoDB Node.js team is pleased to announce version 6.20.0 of the mongodb package!
Release Notes
Collection and Db objects now provide references to their Db and MongoClient
import { MongoClient } from 'mongodb';
const client = new MongoClient(process.env.MONGODB_URI);
const db = client.db('test');
assert(db.client === client); // returns the MongoClient associated with the Db object
const collection = db.collection('test');
assert(collection.db === db); // returns the Db associated with the Collection objectHint is supported with unacknowledged writes for delete, update and findAndModify commands on servers that support hint
The driver no longer throws errors when hint is provided to unacknowledged writes for delete, update and findAndModify commands in the following circumstances:
- No error is thrown for
updatecommands. - No errors are thrown for
deleteandfindAndModifycommands on servers >=4.4.
ServerCapabilities and ReadPreference.minWireVersion are deprecated
Neither the ServerCapabilities class nor the ReadPreference.minWireVersion property were ever intended for public use and, internally, are effectively dead code with the driver's minimum supported server version being 4.2.
Driver info and metadata MongoClient options have been deprecated.
These will be made internal in a future major release:
driverInfoadditionalDriverInfometadataextendedMetadata
CommandOperationOptions.retryWrites is deprecated
CommandOperationOptions.retryWrites is deprecated. This per‑command option has no effect; the Node.js driver only honors retryWrites when configured at the client level (MongoClient options) or via the connection string. Do not use this option on individual commands. There is no runtime behavior change because it was already ignored, but it will be removed in an upcoming major release and may cause type or build errors in code that references it. To control retryable writes, set retryWrites in MongoClient options or include retryWrites=true|false in the connection string.
ChangeStream .tryNext() now updates resumeToken to prevent duplicates after resume
When .tryNext() returns a change document, the driver now caches its resumeToken, aligning its behavior with .next() and the 'change' event. If .tryNext() returns null (no new changes), nothing is cached, which is unchanged from previous behavior.
Previously, .tryNext() did not update the resumeToken, so a resumable error could cause a resume from an older token and re-deliver already processed changes. With this release, resumes continue from the latest token observed via .tryNext(), preventing duplicates.
const changeStream = collection.watch([]);
while (true) {
const change = await changeStream.tryNext(); // prior versions could return duplicates
await scheduler.wait(1000); // delay since tryNext() does not wait for changes
}Applications that poll change streams with .tryNext() in non-blocking loops benefit directly. There are no API changes; if you previously tracked and passed resumeAfter or startAfter manually, you can now rely on the driver’s built-in token caching.
Huge thanks to @rkistner for bringing this bug to our attention and for sharing code to reproduce it. Huge thanks as well to @Omnicpie for investigating and implementing a fix.
Change Streams now resume on MongoServerSelectionError
When the driver encounters a MongoServerSelectionError while processing a Change Stream (e.g., due to a transient network issue or during an election), it now treats the error as resumable and attempts to resume using the latest cached resume token.
This applies to both iterator and event-emitter usage:
// Iterator form
const changeStream = collection.watch([]);
for await (const change of changeStream) {
// process change
}// Event-emitter form
const changeStream = collection.watch([]);
changeStream.on('change', (change) => {
// process change
});There are no API changes. If you previously caught MongoServerSelectionError and implemented manual resume logic, you can now rely on the driver’s built-in resume mechanism, which uses the cached resume token from the change event’s _id to continue without losing events.
Huge thanks to @grossbart for bringing this bug to our attention, investigating it and for sharing code to reproduce it!
MongoClient.appendMetadata() ignores duplicate metadata
MongoClient.appendMetadata() will no longer append metadata if it duplicates the metadata already appended to the MongoClient.
Features
- NODE-7125: add db and client properties to collection and database objects (#4640) (3469f86)
- NODE-7134: allow hint with unacknowledged writes for delete, update and findAndModify commands (#4647) (82d6ce6)
- NODE-7139: remove pre-4.2 logic and deprecate dead code (#4657) (14303bc)
- NODE-7140: deprecate driver info options (#4654) (b813c85)
- NODE-7157: deprecate
retryWritesinCommandOperationOptions(#4661) (620972d)
Bug Fixes
- NODE-4763: cache
resumeTokeninChangeStream.tryNext()(#4636) (8331a93) - NODE-6858: treat MongoServerSelectionError as a resumable error for Change Streams (#4653) (c6d64e7)
- NODE-7138: prevent duplicate metadata from being appended to handshake metadata (#4651) (05c230c)
Documentation
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
v6.19.0
6.19.0 (2025-08-26)
The MongoDB Node.js team is pleased to announce version 6.19.0 of the mongodb package!
Release Notes
Experimental Support for Queryable Encryption Text Field Prefix, Suffix and Substring Queries
Important
Substring, prefix and suffix search are in preview and should be used for experimental workloads only. These features are unstable and their security is not guaranteed until released as Generally Available (GA). The GA version of these features may not be backwards compatible with the preview version.
When using Queryable Encryption with both automatic encryption and explicit encryption, text fields can now be queried using prefix, suffix and substring queries. This feature requires mongodb-client-encryption@>=6.5.0.
Allow a secureContext for Auto Encryption and Client Encryption TLS options
This can be provided in the tlsOptions option both both objects.
import * as tls from 'tls';
import { ClientEncryption, MongoClient } from 'mongodb';
const caFile = await fs.readFile(process.env.CSFLE_TLS_CA_FILE);
const certFile = await fs.readFile(process.env.CSFLE_TLS_CLIENT_CERT_FILE);
const secureContextOptions = {
ca: caFile,
key: certFile,
cert: certFile
};
const options = {
keyVaultNamespace: 'db.coll',
kmsProviders: {
aws: {}
}
},
tlsOptions: {
aws: {
secureContext: tls.createSecureContext(secureContextOptions),
}
}
};
const client = this.configuration.newClient({}, { autoEncryption: { ...options, schemaMap } });
const clientEncryption = new ClientEncryption(client, options);collection.findOne() and collection.find() will no longer potentially leave open cursors on the server
The findOne command will now always set the limit option to 1 and singleBatch to true. The limit, noCursorResponse and batchSize options have also been deprecated, and the command will guarantee no more cursors can be orphaned and no killCursors command will be potentially executed.
find will now set limit to batchSize + 1 when both options were equal, to avoid leaving cursors open.
Clients no longer send a ping on connect
When authentication is enabled, the MongoClient will no longer send a ping command when connecting since it is unnecessary. Instead it will check a connection out of the pool to force the initial handshake, and check it back in.
Features
- NODE-4179: allow secureContext in KMS TLS options (#4578) (0ea6eaa)
- NODE-6472: findOne and find no longer keep open cursors (#4580) (be7f808)
- NODE-7020: remove ping on connect (#4607) (3d296b7)
- NODE-7059, NODE-7008: add support for text queries for QE string fields (#4597) (e4492f3)
Documentation
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
v6.18.0
6.18.0 (2025-07-22)
The MongoDB Node.js team is pleased to announce version 6.18.0 of the mongodb package!
Release Notes
New appendMetadata API allows clients to add handshake metadata post construction
Driver information such as name, version, and platform are allowed:
import { MongoClient } from 'mongodb';
const client = new MongoClient(process.env.MONGODB_URI);
client.appendMetadata({ name: 'my library', version: '1.0', platform: 'NodeJS' });Cursors lazily instantiate sessions
In previous versions, sessions were eagerly allocated whenever a cursor was created, regardless of whether or not a cursor was actually iterated (and the session was actually needed). Some driver APIs (FindCursor.count(), AggregationCursor.explain() and FindCursor.explain()) don't actually iterate the cursor they are executed on. This can lead to client sessions being created and never being cleaned up.
With this update, sessions are not allocated until the cursor is iterated.
Idle connections are now pruned during periods of no activity even when minPoolSize=0
A MongoClient configured with a maxIdleTimeMS and minPoolSize of 0 is advantageous for workloads that have sustained periods of little or no activity because it allows the connection pool to close connections that are unused during these periods of inactivity. However, due to a bug in the ConnectionPool implementation, idle / perished connections were not cleaned up unless minPoolSize was non-zero.
With the changes in this PR, the ConnectionPool now always cleans up idle connections, regardless of minPoolSize.
ChangeStream event interfaces include a wallTime property
This property is available on all types with the exception of reshard collection and refine collection shard key events. Thanks to @qhello for bringing this bug to our attention!
CommandSucceededEvent and CommandFailedEvent events now have a databaseName property
CommandSucceededEvent and CommandFailedEvent now include the name of the database against which the command was executed.
Deprecations
Transaction state getters are deprecated
These were for internal use only and include:
Transaction#options
Transaction#recoveryToken
Transaction#isPinned
Transaction#isStarting
Transaction#isActive
Transaction#isCommittedClientMetadata, ClientMetadataOptions, and CancellationToken have been deprecated
These types will be removed in an upcoming major version of the driver.
CommandOptions.noResponse is deprecated
Caution
noResponse is not intended for use outside of MongoClient.close(). Do not use this option.
The Node driver has historically supported an option, noResponse, that is used internally when a MongoClient is closed. This option was accidentally public. This option will be removed in an upcoming major release.
Features
- NODE-5055: Add databaseName property to command monitoring events (#4586) (3faf0c9)
- NODE-7009: add client metadata on demand (#4574) (b9636ee)
- NODE-7053: deprecate noResponse option (#4589) (1115319)
- NODE-6865: deprecate transaction getters (#4567) (da46aea)
- NODE-6991: deprecate unintentionally public client metadata types (#4566) (ca6554b)
Bug Fixes
- NODE-4845: allocate sessions lazily in cursors (#4575) (5761703)
- NODE-6589: background task does not prune idle connections when minPoolSize=0 (#4569) (7cbb641)
- NODE-6955: add missing
wallTimeproperty TS change stream event interfaces (#4541) (f153c6f)
Documentation
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
v6.17.0
6.17.0 (2025-06-03)
The MongoDB Node.js team is pleased to announce version 6.17.0 of the mongodb package!
Release Notes
Support for MongoDB 4.0 is removed
Warning
When the driver connects to a MongoDB server of version 4.0 or less, it will now throw an error.
OIDC machine workflows now retry on token expired errors during initial authentication
This resolves issues of a cached OIDC token in the driver causing initial authentication to fail when the token had expired. The affected environments were "azure", "gcp", and "k8s".
keepAliveInitialDelay may now be configured at the MongoClient level
When not present will default to 120 seconds. The option value must be specified in milliseconds.
import { MongoClient } from 'mongodb';
const client = new MongoClient(process.env.MONGODB_URI, { keepAliveInitialDelay: 100000 });updateOne and replaceOne now support a sort option
The updateOne and replaceOne operations in each of the ways they can be performed support a sort option starting in MongoDB 8.0. The driver now supports the sort option the same way it does for find or findOneAndModify-style commands:
const sort = { fieldName: -1 };
collection.updateOne({}, {}, { sort });
collection.replaceOne({}, {}, { sort });
collection.bulkWrite([
{ updateOne: { filter: {}, update: {}, sort } },
{ replaceOne: { filter: {}, replacement: {}, sort } },
]);
client.bulkWrite([
{ name: 'updateOne', namespace: 'db.test', filter: {}, update: {}, sort },
{ name: 'replaceOne', namespace: 'db.test', filter: {}, replacement: {}, sort }
]);MongoClient close shuts outstanding in-use connections
The MongoClient.close() method now shuts connections that are in-use allowing the event loop to close if the only remaining resource was the MongoClient.
Support Added for Configuring the DEK cache expiration time.
Default value is 60000. Requires using mongodb-client-encryption >= 6.4.0
For ClientEncryption:
import { MongoClient, ClientEncryption } from 'mongodb';
const client = new MongoClient(process.env.MONGODB_URI);
const clientEncryption = new ClientEncryption(client, { keyExpirationMS: 100000, kmsProviders: ... });For auto encryption:
import { MongoClient, ClientEncryption } from 'mongodb';
const client = new MongoClient(process.env.MONGODB_URI, {
autoEncryption: {
keyExpirationMS: 100000,
kmsProviders: ...
}
});Update operations will now throw if ignoreUndefined is true and all operations are undefined.
When using any of the following operations they will now throw if all atomic operations in the update are undefined and the ignoreUndefined option is true. This is to avoid accidental replacement of the entire document with an empty document. Examples of this scenario:
import { MongoClient } from 'mongodb';
const client = new MongoClient(process.env.MONGODB_URI);
client.bulkWrite(
[
{
name: 'updateMany',
namespace: 'foo.bar',
filter: { age: { $lte: 5 } },
update: { $set: undefined, $unset: undefined }
}
],
{ ignoreUndefined: true }
);
const collection = client.db('test').collection('test');
collection.bulkWrite(
[
{
updateMany: {
filter: { age: { $lte: 5 } },
update: { $set: undefined, $unset: undefined }
}
}
],
{ ignoreUndefined: true }
);
collection.findOneAndUpdate(
{ a: 1 },
{ $set: undefined, $unset: undefined },
{ ignoreUndefined: true }
);
collection.updateOne({ a: 1 }, { $set: undefined, $unset: undefined }, { ignoreUndefined: true });
collection.updateMany({ a: 1 }, { $set: undefined, $unset: undefined }, { ignoreUndefined: true });Socket errors are always treated as network errors
Network errors perform an important role in the driver, impacting topology monitoring processes and retryablity. A bug in the driver's socket implementation meant that in scenarios where server disconnects occurred while no operation was in progress on the socket resulted in errors that were not considered network errors.
Socket errors are now unconditionally treated as network errors.
Features
- NODE-6245: add keepAliveInitialDelay config (#4510) (d6c0eb3)
- NODE-6290: add sort support to updateOne and replaceOne (#4515) (28857b7)
- NODE-6882: eagerly close checked out connections when client is closed (#4499) (64fdb3e)
- NODE-6884: remove support for 4.0 (#4534) (6fe6ccc)
- NODE-6952: support configuring DEK cache expiration (#4538) (c529f07)
- NODE-6963: use BSON 6.10.4 (#4549) (aee490a)
Bug Fixes
- NODE-6638: throw if all atomic updates are undefined (#4519) (9625b2d)
- NODE-6864: socket errors are not always converted to MongoNetworkErrors (#4473) (2d86095)
- NODE-6962: OIDC machine workflows use OIDCCallbacks internally (#4546) (bd6030f)
Documentation
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
v6.16.0
6.16.0 (2025-04-21)
The MongoDB Node.js team is pleased to announce version 6.16.0 of the mongodb package!
Release Notes
distinct commands now support an index hint
The Collection.distinct() method now supports an optional hint, which can be used to tell the server which index to use for the command:
// providing an index description
await collection.distinct('my-key', {
hint: { 'my-key': 1 }
});
// providing an index name
await collection.distinct('my-key', {
hint: 'my-key'
});This requires server 7.1+.
Driver support for servers <=4.0 deprecated
Warning
Node driver support for server 4.0 will be removed in an upcoming minor release. Reference: MongoDB Software Lifecycle Schedules.
Fix processing of multiple messages within one network data chunk
During elections, or other scenarios where the server is pushing multiple topology updates to the driver in a short period of time, a bug in the driver's socket code led to backlog of topology updates that would remain in the buffer until another heartbeat arrived from the server. This could lead to delays in the driver recovering from an election and/or an increase in MongoServerSelectionErrors.
Now, all messages in the current buffer are returned to the driver leading to faster processing times.
Huge thank you to @andreim-brd for sharing a self-contained reproduction that proved to be instrumental in the identification of the underlying issue!
FindCursor.rewind() throws documents?.clear() is not a function errors in certain scenarios
In certain scenarios where limit and batchSize are both set on a FindCursor, an internal driver optimization intended to prevent unnecessary requests to the server when the driver knows the cursor is exhausted would prevent the cursor from being rewound. This issue has been resolved.
Features
- NODE-6494: add support for
hinton distinct commands (#4487) (40d0e87) - NODE-6515: deprecate driver support for server 4.0 (#4517) (4c1a8a7)
Bug Fixes
- NODE-6630: read all messages in buffer when chunk arrives (#4512) (8c86e30)
- NODE-6878: documents.clear() throws a TypeError after cursor is rewound (#4488) (a1fffeb)
Documentation
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
v6.15.0
6.15.0 (2025-03-18)
The MongoDB Node.js team is pleased to announce version 6.15.0 of the mongodb package!
Release Notes
Support for custom AWS credential providers
The driver now supports a user supplied custom AWS credentials provider for both authentication and for KMS requests when using client side encryption. The signature for the custom provider must be of () => Promise<AWSCredentials> which matches that of the official AWS SDK provider API. Provider chains from the actual AWS SDK can also be provided, allowing users to customize any of those options.
Example for authentication with a provider chain from the AWS SDK:
import { fromNodeProviderChain } from '@aws-sdk/credential-providers';
const client = new MongoClient(process.env.MONGODB_URI, {
authMechanismProperties: {
AWS_CREDENTIAL_PROVIDER: fromNodeProviderChain()
}
});Example for using a custom provider for KMS requests only:
import { fromNodeProviderChain } from '@aws-sdk/credential-providers';
const client = new MongoClient(process.env.MONGODB_URI, {
autoEncryption: {
keyVaultNamespace: 'keyvault.datakeys',
kmsProviders: { aws: {} },
credentialProviders: {
aws: fromNodeProviderChain()
}
}
}Custom providers do not need to come from the AWS SDK, they just need to be an async function that returns credentials:
const client = new MongoClient(process.env.MONGODB_URI, {
authMechanismProperties: {
AWS_CREDENTIAL_PROVIDER: async () => {
return {
accessKeyId: process.env.ACCESS_KEY_ID,
secretAccessKey: process.env.SECRET_ACCESS_KEY
}
}
}
});Fix misc unhandled rejections under special conditions
We identified an issue with our test suite that suppressed catching unhandled rejections and surfacing them to us so we can ensure the driver handles any possible rejections. Luckily only 3 cases were identified and each was under a flagged or specialized code path that may not have been in use:
- If the MongoClient was configured to use
OIDCand anAbortSignalwas aborted on cursor at the same time the client was reauthenticating, if the reauth process was rejected it would have been unhandled. - If
timeoutMSwas used and the timeout expired before an operation reached the server selection step the operation would throw the expected timeout error but a promise representing the timeout would also raise an unhandled rejection. - If a change stream was closed while processing a change event it was possible for the "change stream is closed" error to be emitted as an error event and reject an internal promise representing fetching the "next" change.
Features
Bug Fixes
Documentation
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
v6.14.2
6.14.2 (2025-03-04)
The MongoDB Node.js team is pleased to announce version 6.14.2 of the mongodb package!
Release Notes
KMS Requests can cause unhandled rejection
When using explicit encryption or automatic encryption, the driver makes requests to a Key Management System when to fetch key encryption keys. The driver supports connecting to a KMS provider through a Socks5 proxy. However, the socket used for the socks5 proxy was created in all circumstances, regardless of proxy configuration. This leads to unhandled rejection errors when closing the socket the driver attempts to clean up the unused socket.
With the changes in this release, the socket is only created if a proxy is configured and the any promises created for the proxy are properly handled.
Bug Fixes
Documentation
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
v6.14.1
6.14.1 (2025-03-03)
The MongoDB Node.js team is pleased to announce version 6.14.1 of the mongodb package!
Release Notes
Fixed occasional OIDC reauthentication failure
Error code 391 is intended to make the driver internally reauthenticate the connection to the server, however, occasionally this was being raised to the user. This was due to a bug in setting the cached access token on newly created connections.
Bug Fixes
Documentation
We invite you to try the mongodb library immediately, and report any issues to the NODE project.