NewYour coding agent can read the release notes before it upgrades.Set up the MCP server →
npm · #3169 most downloaded on npm
The official MongoDB driver for Node.js
Last release today
04 Oct 2026
Ships on a steady schedule
a new release about every 8 days
Nearly every release is documented
notes for 60 of the last 60 stable releases
195 versions withdrawn
withdrawn after publishing
15 years old
922 releases · first in 2011
Nothing published for this version
Nothing published for this version
Nothing published for this version
One column per quarter.
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
The MongoDB Node.js team is pleased to announce version 6.2.0 of the mongodb package!
The MongoDB Node.js team is pleased to announce version 6.2.0 of the mongodb package!
BSON now prints in full color! :rainbow: :rocket:
<img src="https://github.com/mongodb/node-mongodb-native/assets/10873993/b32cd46e-518b-477a-b976-76930b743d01" width="580" height="28">
See our release notes for BSON 6.2.0 here for more examples!
insertedIds in bulk write now contain only successful insertionsPrior to this fix, the bulk write error's result.insertedIds property contained the _id of each attempted insert in a bulk operation.
Now, when a bulkwrite() or an insertMany() operation rejects one or more inserts, throwing an error, the error's result.insertedIds property will only contain the _id fields of successfully inserted documents.
findOne()When running a findOne against a time series collection, the driver left the implicit session for the cursor un-ended due to the way the server returns the resulting cursor information. Now the cursor will always be cleaned up regardless of the outcome of the find operation.
Database and collection name checking will now be in sync with the MongoDB server's naming restrictions. Specifically, users can now create collections that start or end with the '.' character.
awaited field to SDAM heartbeat events (#3895) (b50aadc)We invite you to try the mongodb library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 6.1.0 of the mongodb package!
The MongoDB Node.js team is pleased to announce version 6.1.0 of the mongodb package!
Decimal128.fromStringWithRounding() methodIn this release, we have adopted the changes made to Decimal128 in bson version 6.1.0. We have added a new fromStringWithRounding() method which exposes the previously available inexact rounding behaviour.
See the bson v6.1.0 release notes for more information.
When using IAM AssumeRoleWithWebIdentity AWS authentication the driver uses the @aws-sdk/credential-providers package to contact the Security Token Service API for temporary credentials. AWS recommends using Regional AWS STS endpoints instead of the global endpoint to reduce latency, build-in redundancy, and increase session token validity. Unfortunately, environment variables AWS_STS_REGIONAL_ENDPOINTS and AWS_REGION do not directly control the region the SDK's STS client contacts for credentials.
The driver now has added support for detecting these variables and setting the appropriate options when calling the SDK's API: fromNodeProviderChain().
[!IMPORTANT] The driver will only set region options if BOTH environment variables are present.
AWS_STS_REGIONAL_ENDPOINTSMUST be set to either'legacy'or'regional', andAWS_REGIONmust be set.
In a previous release, 5.7.0, we refactored cursor internals from callbacks to async/await. In particular, the next function that powers cursors was written with callbacks and would recursively call itself depending on the cursor type. For ChangeStreams, this function would call itself if there were no new changes to return to the user. After converting that code to async/await each recursive call created a new promise that saved the current async context. This would slowly build up memory usage if no new changes came in to unwind the recursive calls.
The function is now implemented as a loop, memory leak be gone!
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
Previously, this function returned void this is a feature to align with the following breaking change.
The MongoDB Node.js team is pleased to announce version 6.0.0 of the mongodb package!
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 v5.8.1 of the driver. ALL changes listed below are BREAKING. Users migrating from an older version of the driver are advised to upgrade to at least v5.8.1 before adopting v6.
The minimum supported Node.js version is now v16.20.1. 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.
This driver version has been updated to use bson@6.0.0. BSON functionality re-exported from the driver is subject to the changes outlined in the BSON V6 release notes.
kerberos optional peer dependency minimum version raised to 2.0.1, dropped support for 1.xzstd optional peer depedency minimum version raised to 1.1.0 from 1.0.0mongodb-client-encryption optional peer dependency minimum version raised to 6.0.0 from 2.3.0 (note that mongodb-client-encryption does not have 3.x-5.x version releases)[!NOTE] As of version 6.0.0, all useful public APIs formerly exposed from
mongodb-client-encryptionhave been moved into the driver and should now be imported directly from the driver. These APIs rely internally on the functionality exposed frommongodb-client-encryption, but there is no longer any need to explicitly referencemongodb-client-encryptionin your application code.
socks to be installed optionallyThe driver uses the socks dependency to connect to mongod or mongos through a SOCKS5 proxy. socks used to be a required dependency of the driver and was installed automatically. Now, socks is a peerDependency that must be installed to enable socks proxy support.
findOneAndX family of methods will now return only the found document or null by default (includeResultMetadata is false by default)Previously, the default return type of this family of methods was a ModifyResult containing the found document and additional metadata. This additional metadata is unnecessary for the majority of use cases, so now, by default, they will return only the found document or null.
The previous behavior is still available by explicitly setting includeResultMetadata: true in the options.
See the following blog post for more information.
// This has the same behaviour as providing `{ includeResultMetadata: false }` in the v5.7.0+ driver
await collection.findOneAndUpdate({ hello: 'world' }, { $set: { hello: 'WORLD' } });
// > { _id: new ObjectId("64c4204517f785be30795c92"), hello: 'world' }
// This has the same behaviour as providing no options in any previous version of the driver
await collection.findOneAndUpdate(
{ hello: 'world' },
{ $set: { hello: 'WORLD' } },
{ includeResultMetadata: true }
);
// > {
// > lastErrorObject: { n: 1, updatedExisting: true },
// > value: { _id: new ObjectId("64c4208b17f785be30795c93"), hello: 'world' },
// > ok: 1
// > }
session.commitTransaction() and session.abortTransaction() return voidEach of these methods erroneously returned server command results that can be different depending on server version or type the driver is connected to. These methods return a promise that if resolved means the command (aborting or commiting) sucessfully completed and rejects otherwise. Viewing command responses is possible through the command monitoring APIs on the MongoClient.
withSession and withTransaction return the value returned by the provided functionThe await client.withSession(async session => {}) now returns the value that the provided function returns. Previously, this function returned void this is a feature to align with the following breaking change.
The await session.withTransaction(async () => {}) method now returns the value that the provided function returns. Previously, this function returned the server command response which is subject to change depending on the server version or type the driver is connected to. The return value got in the way of writing robust, reliable, consistent code no matter the backing database supporting the application.
[!WARNING] When upgrading to this version of the driver, be sure to audit any usages of
withTransactionforifstatements or other conditional checks on the return value ofwithTransaction. Previously, the return value was the command response if the transaction was committed andundefinedif it had been manually aborted. It would only throw if an operation or the author of the function threw an error. Since prior to this release it was not possible to get the result of the function passed towithTransactionwe suspect most existing functions passed to this method returnvoid, makingwithTransactionavoidreturning function in this major release. Take care to ensure that the return values of your function match the expectation of the code that follows the completion ofwithTransaction.
MongoClientProviding a session from one MongoClient to a method on a different MongoClient has never been a supported use case and leads to undefined behavior. To prevent this mistake, the driver now throws a MongoInvalidArgumentError if session is provided to a driver helper from a different MongoClient.
// pre v6
const session = client1.startSession();
client2.db('foo').collection('bar').insertOne({ name: 'john doe' }, { session }); // no error thrown, undefined behavior
// v6+
const session = client1.startSession();
client2.db('foo').collection('bar').insertOne({ name: 'john doe' }, { session });
// MongoInvalidArgumentError thrown
encrypt, decrypt, and createDataKey methodsDriver v5 dropped support for callbacks in asynchronous functions in favor of returning promises in order to provide more consistent type and API experience. In alignment with that, we are now removing support for callbacks from the ClientEncryption class.
MongoCryptError is now a subclass of MongoErrorSince MongoCryptError made use of Node.js 16's Error API, it has long supported setting the Error.cause field using options passed in via the constructor. Now that Node.js 16 is our minimum supported version, MongoError has been modified to make use of this API as well, allowing us to let MongoCryptError subclass from it directly.
useNewUrlParser and useUnifiedTopology emit deprecation warningsThese options were removed in 4.0.0 but continued to be parsed and silently left unused. We have now added a deprecation warning through Node.js' warning system and will fully remove these options in the next major release.
Prior to this change, we accepted the values '1', 'y', 'yes', 't' as synonyms for true and '-1', '0', 'f', 'n', 'no' as synonyms for false. These have now been removed in an effort to make working with connection string options simpler.
// Incorrect
const client = new MongoClient('mongodb://localhost:27017?tls=1'); // throws MongoParseError
// Correct
const client = new MongoClient('mongodb://localhost:27017?tls=true');
In order to avoid accidental misconfiguration the driver will no longer prioritize the first instance of an option provided on the URI. Instead repeated options that are not permitted to be repeated will throw an error.
This change will ensure that connection strings that contain options like tls=true&tls=false are no longer ambiguous.
In order to align with Node.js best practices of keeping I/O async, we have updated the MongoClient to store the file names provided to the existing tlsCAFile and tlsCertificateKeyFile options, as well as the tlsCRLFile option, and only read these files the first time it connects. Prior to this change, the files were read synchronously on MongoClient construction.
[!NOTE] This has no effect on driver functionality when TLS configuration files are properly specified. However, if there are any issues with the TLS configuration files (invalid file name), the error is now thrown when the
MongoClientis connected instead of at construction time.
const client = new MongoClient(CONNECTION_STRING, {
tls: true,
tlsCAFile: 'caFileName',
tlsCertificateKeyFile: 'certKeyFile',
tlsCRLFile: 'crlPemFile'
}); // Files are not read here, but file names are stored on the MongoClient
await client.connect(); // Files are now read and their contents stored
await client.close();
await client.connect(); // Since the file contents have already been cached, the files will not be read again.
Take a look at our TLS documentation for more information on the tlsCAFile, tlsCertificateKeyFile, and tlsCRLFile options.
These APIs allow for specifying a command BSON document directly, so the driver does not try to enumerate all possible commands that could be passed to this API in an effort to be as forward and backward compatible as possible.
The db.command() and admin.command() APIs have their options types updated to accurately reflect options compatible on all commands that could be passed to either API.
Perhaps most notably, readConcern and writeConcern options are no longer handled by the driver. Users must attach these properties to the command that is passed to the .command() method.
ConnectionPoolCreatedEvent.optionsThe options field of ConnectionPoolCreatedEvent now has the following shape:
{
maxPoolSize: number,
minPoolSize: number,
maxConnecting: number,
maxIdleTimeMS: number,
waitQueueTimeoutMS: number
}
The following connection string will now produce the following readPreferenceTags:
'mongodb://host?readPreferenceTags=region:ny&readPreferenceTags=rack:r1&readPreferenceTags=';
// client.options.readPreference.tags
[{ region: 'ny' }, { rack: 'r1' }, {}];
The empty readPreferenceTags allows drivers to still select a server if the leading tag conditions are not met.
GridFSBucketWriteStream's Writable method overrides and event emissionOur implementation of a writeable stream for GridFSBucketWriteStream mistakenly overrode the write() and end() methods, as well as, manually emitted 'close', 'drain', 'finish' events. Per Node.js documentation, these methods and events are intended for the Node.js stream implementation to provide, and an author of a stream implementation is supposed to override _write, _final, and allow Node.js to manage event emitting.
Since the API is still a Writable stream most usages will continue to work with no changes, the .write() and .end() methods are still available and take the same arguments. The breaking change relates to the improper manually emitted event listeners that are now handled by Node.js. The 'finish' and 'drain' events will no longer receive the GridFSFile document as an argument (this is the document inserted to the bucket's files collection after all chunks have been inserted). Instead, it will be available on the stream itself as a property: gridFSFile.
// If our event handler is declared as a `function` "this" is bound to the stream.
fs.createReadStream('./file.txt')
.pipe(bucket.openUploadStream('file.txt'))
.on('finish', function () {
console.log(this.gridFSFile);
});
// If our event handler is declared using big arrow notation,
// the property is accessible on a scoped variable
const uploadStream = bucket.openUploadStream('file.txt');
fs.createReadStream('./file.txt')
.pipe(uploadStream)
.on('finish', () => console.log(uploadStream.gridFSFile));
Since the class no longer emits its own events: static constants GridFSBucketWriteStream.ERROR, GridFSBucketWriteStream.FINISH, GridFSBucketWriteStream.CLOSE have been removed to avoid confusion about the source of the events and the arguments their listeners accept.
GridFSBucketReadStreamThe GridFSBucketReadStream internals have also been corrected to no longer emit events that are handled by Node's stream logic. Since the class no longer emits its own events: static constants GridFSBucketReadStream.ERROR, GridFSBucketReadStream.DATA, GridFSBucketReadStream.CLOSE, and GridFSBucketReadStream.END have been removed to avoid confusion about the source of the events and the arguments their listeners accept.
createDataKey return type fixPreviously, the TypeScript for createDataKey incorrectly declared the result to be a DataKey but the method actually returns the DataKey's insertedId.
db.addUser() and admin.addUser() removedThe deprecated addUser APIs have been removed. The driver maintains support across many server versions and the createUser command has support for different features based on the server's version. Since applications can generally write code to work against a uniform and perhaps more modern server, the path forward is for applications to send the createUser command directly.
The associated options interface with this API has also been removed: AddUserOptions.
See the createUser documentation for more information.
const db = client.db('admin');
// Example addUser usage
await db.addUser('myUsername', 'myPassword', { roles: [{ role: 'readWrite', db: 'mflix' }] });
// Example equivalent command usage
await db.command({
createUser: 'myUsername',
pwd: 'myPassword',
roles: [{ role: 'readWrite', db: 'mflix' }]
});
collection.stats() removedThe collStats command is deprecated starting in server v6.2 so the driver is removing its bespoke helper in this major release. The collStats command is still available to run manually via await db.command(). However, the recommended migration is to use the $collStats aggregation stage.
The following interfaces associated with this API have also been removed: CollStatsOptions and WiredTigerData.
BulkWriteResult deprecated properties removedThe following deprecated properties have been removed as they duplicated those outlined in the [MongoDB CRUD specification|https://github.com/mongodb/specifications/blob/611ecb5d624708b81a4d96a16f98aa8f71fcc189/source/crud/crud.rst#write-results]. The list indicates what properties provide the correct migration:
BulkWriteResult.nInserted -> BulkWriteResult.insertedCountBulkWriteResult.nUpserted -> BulkWriteResult.upsertedCountBulkWriteResult.nMatched -> BulkWriteResult.matchedCountBulkWriteResult.nModified -> BulkWriteResult.modifiedCountBulkWriteResult.nRemoved -> BulkWriteResult.deletedCountBulkWriteResult.getUpsertedIds -> BulkWriteResult.upsertedIds / BulkWriteResult.getUpsertedIdAt(index: number)BulkWriteResult.getInsertedIds -> BulkWriteResult.insertedIdsThe following options have been removed with their supported counterparts listed after the ->
sslCA -> tlsCAFilesslCRL -> tlsCRLFilesslCert -> tlsCertificateKeyFilesslKey -> tlsCertificateKeyFilesslPass -> tlsCertificateKeyFilePasswordsslValidate -> tlsAllowInvalidCertificatestlsCertificateFile -> tlsCertificateKeyFilekeepAlive and keepAliveInitialDelay options have been removedTCP keep alive will always be on and now set to a value of 30000ms.
The removed functionality listed in this section was either unused or not useful outside the driver internals.
MongoError and its subclasses now clearly indicate they are meant for internal use onlyMongoError and its subclasses are not meant to be constructed by users as they are thrown within the driver on specific error conditions to allow users to react to these conditions in ways which match their use cases. The constructors for these types are now subject to change outside of major versions and their API documentation has been updated to reflect this.
AutoEncrypter and MongoClient.autoEncrypter are now internalAs of this release, users will no longer be able to access the AutoEncrypter interface or the MongoClient.autoEncrypter field of an encrypted MongoClient instance as they do not have a use outside the driver internals.
ClientEncryption.onKMSProvidersRefresh function removedClientEncryption.onKMSProvidersRefresh was added as a public API in version 2.3.0 of mongodb-client-encryption to allow for automatic refresh of KMS provider credentials. Subsequently, we added the capability to automatically refresh KMS credentials using the KMS provider's preferred refresh mechanism, and onKMSProviderRefresh is no longer used.
EvalOptions removedThis cleans up some dead code in the sense that there were no eval command related APIs but the EvalOptions type was public, so we want to ensure there are no surprises now that this type has been removed.
onKMSProvidersRefresh (#3787)We invite you to try the mongodb library immediately, and report any issues to the NODE project.
Nothing published for this version
Nothing published for this version
Nothing published for this version
The MongoDB Node.js team is pleased to announce version 5.9.2 of the mongodb package!
The MongoDB Node.js team is pleased to announce version 5.9.2 of the mongodb package!
When enabling serverApi the driver's RTT mesurment logic (used to determine the closest node) still sent the legacy hello command "isMaster" causing the server to return an error. Unfortunately, the error handling logic did not correctly destroy the socket which would cause a leak.
Both sending the correct hello command and the error handling connection clean up logic are fixed in this change.
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 5.9.1 of the mongodb package!
The MongoDB Node.js team is pleased to announce version 5.9.1 of the mongodb package!
insertedIds in bulk write now contain only successful insertionsPrior to this fix, the bulk write error's result.insertedIds property contained the _id of each attempted insert in a bulk operation.
Now, when a bulkwrite() or an insertMany() operation rejects one or more inserts, throwing an error, the error's result.insertedIds property will only contain the _id fields of successfully inserted documents.
findOne()When running a findOne against a time series collection, the driver left the implicit session for the cursor un-ended due to the way the server returns the resulting cursor information. Now the cursor will always be cleaned up regardless of the outcome of the find operation.
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 5.9.0 of the mongodb package!
The MongoDB Node.js team is pleased to announce version 5.9.0 of the mongodb package!
bson version to make use of new Decimal128 behaviourIn this release, we have adopted the changes made to Decimal128 in bson version 5.5. The Decimal128 constructor and fromString() methods now throw when detecting a loss of precision (more than 34 significant digits). We also expose a new fromStringWithRounding() method which restores the previous rounding behaviour.
See the bson v5.5.0 release notes for more information.
When using IAM AssumeRoleWithWebIdentity AWS authentication the driver uses the @aws-sdk/credential-providers package to contact the Security Token Service API for temporary credentials. AWS recommends using Regional AWS STS endpoints instead of the global endpoint to reduce latency, build-in redundancy, and increase session token validity. Unfortunately, environment variables AWS_STS_REGIONAL_ENDPOINTS and AWS_REGION do not directly control the region the SDK's STS client contacts for credentials.
The driver now has added support for detecting these variables and setting the appropriate options when calling the SDK's API: fromNodeProviderChain().
[!IMPORTANT] The driver will only set region options if BOTH environment variables are present.
AWS_STS_REGIONAL_ENDPOINTSMUST be set to either'legacy'or'regional', andAWS_REGIONmust be set.
In a previous release, 5.7.0, we refactored cursor internals from callbacks to async/await. In particular, the next function that powers cursors was written with callbacks and would recursively call itself depending on the cursor type. For ChangeStreams, this function would call itself if there were no new changes to return to the user. After converting that code to async/await each recursive call created a new promise that saved the current async context. This would slowly build up memory usage if no new changes came in to unwind the recursive calls.
The function is now implemented as a loop, memory leak be gone!
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 5.8.1 of the mongodb package!
The MongoDB Node.js team is pleased to announce version 5.8.1 of the mongodb package!
saslprep updated to correct library.Fixes the import of saslprep to be the correct @mongodb-js/saslprep library.
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
The AutoEncrypter interface was used internally but accidentally made public in the 4.x version of the driver. It is now deprecated and will be made i…
The MongoDB Node.js team is pleased to announce version 5.8.0 of the mongodb package!
AutoEncrypter interface has been deprecatedThe AutoEncrypter interface was used internally but accidentally made public in the 4.x version of the driver. It is now deprecated and will be made internal in the next major release.
Moves the kerberos dependency back to ^1.0.0 || ^2.0.0 to indicate support for both 1.x and 2.x. Support for 1.x is removed in 6.0.
Because of internal options handling, a deprecation was emitted for tlsCertificateFile when using tlsCertificateKeyFile. That has been corrected.
ConnectionPoolCreatedEventIn order to avoid mistakenly printing credentials the ConnectionPoolCreatedEvent will replace the credentials option with an empty object. The credentials are still accessble via MongoClient options: client.options.credentials.
AutoEncrypter interface (#3764) (9bb0d95)@aws-sdk/credential-providers version to 3.188.0 and zstd to ^1.0.0 (#3821) (39ff81d)We invite you to try the mongodb library immediately, and report any issues to the NODE project.
wtimeout, j, and fsync options have been deprecated, please use wtimeoutMS and journal instead.
The MongoDB Node.js team is pleased to announce version 5.7.0 of the mongodb package!
wtimeout, j, and fsync options have been deprecated, please use wtimeoutMS and journal instead.
In an effort to simplify TLS setup and use with the driver we're paring down the number of custom options to the ones that are common to all drivers. This should reduce inadvertent misconfiguration due to conflicting options.
The legacy "ssl-" options have been deprecated, each has a corresponding "tls-" option listed in the table below (except for sslCRL, you may directly use the Node.js crl option instead). tlsCertificateFile has also been deprecated, please use tlsCertificateKeyFile or pass the cert directly to the MongoClient constructor.
In addition to the common driver options, the Node.js driver also passes through Node.js TLS options provided on the MongoClient to Node.js' tls.connect API, which may be convenient to reuse with other Node.js APIs.
| Node.js native option | MongoDB driver option name | legacy option name | driver option type |
|---|---|---|---|
ca |
tlsCAFile |
sslCA |
string |
crl |
N/A | sslCRL |
string |
cert |
tlsCertificateKeyFile |
sslCert |
string |
key |
tlsCertificateKeyFile |
sslKey |
string |
passphrase |
tlsCertificateKeyFilePassword |
sslPass |
string |
rejectUnauthorized |
tlsAllowInvalidCertificates |
sslValidate |
boolean |
includeResultMetadata option for findOneAnd... family of methods.This option defaults to true, which will return a ModifyResult type. When set to false, which will
become the default in the next major release, it will return the modified document or null if nothing matched.
This applies to findOneAndDelete, findOneAndUpdate, findOneAndReplace.
// With a document { _id: 1, a: 1 } in the collection
await collection.findOneAndDelete({ a: 1 }, { includeResultMetadata: false }); // returns { _id: 1, a: 1 }
await collection.findOneAndDelete({ a: 2 }, { includeResultMetadata: false }); // returns null
await collection.findOneAndDelete({ a: 1 }, { includeResultMetadata: true }); // returns { ok: 1, lastErrorObject: { n: 1 }, value: { _id: 1, a: 1 }}
When change stream documents exceed the max BSON size limit of 16MB, they can be split into multiple fragments in order to not error when sending events over the wire. In order to enable this functionality, the collection must be created with changeStreamPreAndPostImages enabled and the change stream itself must include an $changeStreamSplitLargeEvent aggregation stage. This feature requires a minimum server version of 7.0.0.
Example:
await db.createCollection('test', { changeStreamPreAndPostImages: { enabled: true }});
const collection = db.collection('test');
const changeStream = collection.watch([{ $changeStreamSplitLargeEvent: {} ], {
fullDocumentBeforeChange: 'required'
});
for await (const change of changeStream) {
console.log(change.splitEvent); // If changes over 16MB: { fragment: n, of: n }
}
This PR adds support for managing search indexes (creating, updating, deleting and listing indexes). The new methods are available on the Collection class.
const indexes = await collection.listSearchIndexes().toArray(); // produces an array of search indexes
await collection.createSearchIndex({ name: 'my-index', definition: < index definition > } );
await collection.updateSearchIndex('my-index', < new definition >);
await collection.dropSearchIndex('my-index');
Take a look at the bson package's release notes!
Unlike our other compression mechanisms snappy was loaded at the module level, meaning it would be optionally imported whether or not the driver was configured to use snappy compression. Snappy is now aligned with our other optional peer dependencies and is only loaded when enabled.
This allows users who do not use these features to not have them installed. Users who do use these feature will now have them lazy loaded upon first use.
listDatabases nameOnly option bug fixThe listDatabases API exposes the nameOnly option which allows you to limit its output to only the names of the databases on a given mongoDB deployment:
db.admin().listDatabases({ nameOnly: true });
// [
// { name: 'local' },
// { name: 'movies' },
// ...
// ]
Prior to this fix, the option was not being set properly on the command, so the output was always given in full.
Thanks to @redixhumayun for submitting this fix!
saslprep "is not a function" fix for bundled deploymentssaslprep is an optional dependency used to perform Stringprep Profile for User Names and Passwords for SCRAM-SHA-256 authentication. The saslprep library breaks when it is bundled, causing the driver to throw TypeErrors.
This release includes a fix that prevents the driver throwing TypeErrors when attempting to use saslprep in bundled environments.
The cursor API provides the ability to apply a map function to each document in the cursor:
const cursor = collection.find({ name: 'john doe' }).map(({ name }) => name);
for await (const document of cursor) {
console.error(document); // only prints the `name` field from each document
}
Cursor.mapStarting in version 4.0 of the driver, if the transform function throws an error, there are certain scenarios where the driver does not correctly catch this error and an uncaught exception is thrown:
const cursor = collection.find({ name: 'john doe' }).map(() => {
throw new Error('oh no! error here'); //
});
await cursor.next(); // process crashes with uncaught error
This release adds logic to ensure that whenever we transform a cursor document, we handle any errors properly. Any errors thrown from a transform function are caught and returned to the user.
Version 4.0 introduced a bug that would apply a transform function to documents in the cursor when the cursor was iterated using Cursor.hasNext(). When combined with Cursor.next(), this would result in transforming documents multiple times.
const cursor = collection.find({ name: 'john doe' }).map((document) => document.name);
while (await cursor.hasNext()) { // this transforms the first document in the cursor once
const doc = await cursor.next(); // the second document in the cursor is transformed again
}
This release removes the transform logic from Cursor.hasNext, preventing cursor documents from being transformed twice when iterated using hasNext.
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 5.6.0 of the mongodb package!
The MongoDB Node.js team is pleased to announce version 5.6.0 of the mongodb package!
The MongoDB Node.js Driver now supports Node.js 20! 🎉
runCursorCommand APIWe have added the Db#runCursorCommand method which can be used to execute generic cursor commands. This API complements the generic Db#command method.
The driver now has TypeScript support for the bucketMaxSpanSeconds and bucketRoundingSeconds options which will be available in MongoDB 7.0. You can read more about these options here.
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
Nothing published for this version
Nothing published for this version
The MongoDB Node.js team is pleased to announce version 5.5.0 of the mongodb package!
The MongoDB Node.js team is pleased to announce version 5.5.0 of the mongodb package!
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
The db.command() API has a number of options deprecated that were incorrectly included in the typescript interface the method reportedly accepts. A ma…
The MongoDB Node.js team is pleased to announce version 5.4.0 of the mongodb package!
ChangeStream.tryNext Typescript fixWe have corrected the tryNext method on ChangeStream to use the TChange schema generic instead of the untyped Document interface. This may increase strictness for existing usages but aligns with the rest of the methods on the change stream class to accurately reflect the type returned from the driver.
The db.command() API has a number of options deprecated that were incorrectly included in the typescript interface the method reportedly accepts. A majority of the options relate to fields that must be attached to the command directly: readConcern, writeConcern, and comment.
Additionally, the collStats helper has been deprecated in favor of using database aggregations to get the same result: https://www.mongodb.com/docs/manual/reference/operator/aggregation/collStats/
NOTE: This release includes some experimental features that are not yet ready for production use. As a reminder, anything marked experimental is not a part of the stable driver API and is subject to change without notice.
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
NODE-4774: deprecate cursor forEach
The MongoDB Node.js team is pleased to announce version 5.3.0 of the mongodb package!
upsertedId to be null in UpdateResult (#3631) (4b5be21)We invite you to try the mongodb library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 5.2.0 of the mongodb package!
The MongoDB Node.js team is pleased to announce version 5.2.0 of the mongodb package!
This release includes driver support for automatically obtaining Azure credentials when using automatic client side encryption. You can find a tutorial for using Azure and automatic encryption here: Use Automatic Queryable Encryption with Azure
Additionally, we have a number of minor bug fixes listed below.
NOTE: This release includes some experimental features that are not yet ready for use. As a reminder, anything marked experimental is not a part of the stable driver API and is subject to change without notice.
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 5.1.0 of the mongodb package!
The MongoDB Node.js team is pleased to announce version 5.1.0 of the mongodb package!
bigints in the driverThe driver now supports automatic serialization of JavaScript bigints to BSON.Longs. It also supports deserializing of BSON.Long values returned from the server to bigint values when the useBigInt64 flag is passed as true.
import { MongoClient } from 'mongodb';
(async () => {
const client = new MongoClient('<YOUR CONNECTION STRING>');
const db = client.db('test');
const coll = db.collection('bigints');
await coll.insertOne({ a: 10n }); // The driver automatically serializes bigints to BSON.Long before being sent to the server
const docBigInt = await coll.findOne({ a: 10n }, { useBigInt64: true }); // Must provide the useBigInt64 flag to specify that bigints get returned
console.log(docBigInt);
// { _id: ObjectId(...), a: 10n }
const doc = await coll.findOne({ a: 10n }); // Must provide the useBigInt64 flag to specify that bigints get returned
console.log(doc);
// { _id: ObjectId(...), a: 10 }
await client.close();
})()
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 5.0.1 of the mongodb package!
The MongoDB Node.js team is pleased to announce version 5.0.1 of the mongodb package!
This release reverts a fix that unintentionally caused a leak of internal driver resources.
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
Collection.insert, Collection.update, and Collection.remove methods have been removed in favor of their non-deprecated counterparts. You can read more…
The MongoDB Node.js team is pleased to announce version 5.0.0 of the mongodb package!
Node.js driver v5 emphazises the modernization of our API.
Most notably, we have removed support for callbacks in favor of a Promise-only public API.
To ease the migration to a Promise-only approach when using the Node.js driver, callback support is available via the mongodb-legacy package. You can read more about this change in the Optional callback support migrated to mongodb-legacy section of the migration guide.
Version 4.3.0 of the Node.js driver introduced strict type checking on Filter queries that used dot notation. This functionality was enabled by default and proved to be a barrier for users upgrading to later versions of the Node.js v4.x driver. In order to ease the migration to v5.0.0, type strictness on queries that use dot notation has been removed from the CRUD API. The type checking capabilities are still available in an experimental type called StrictFilter. You can read more about this change in the Dot Notation TypeScript Support Removed By Default section of the migration guide.
This release also adopts all the changes in BSON v5.0.0 (see the release notes).
The driver now exports a BSON namespace that also has BSON.EJSON APIs available.
When working in projects where both the driver and bson are used, we recommend importing BSON types (ObjectId, Long, etc.) and BSON APIs from the driver instead of from BSON directly to ensure consistency when serializing and deserializing instances of the BSON types.
@aws-sdk/credential-providers has now been moved to an optional peer dependency.
Consequently, in v5.0.0 or later versions of the driver, the AWS credential provider module must be installed manually to enable the use of the native AWS SDK for authentication.
Collection.insert, Collection.update, and Collection.remove methods have been removed in favor of their non-deprecated counterparts. You can read more about this and other changes in our Driver v5 Migration Guide.
We invite you to try the mongodb library and report any issues to the NODE project.
This alpha build is intended for internal testing only. Adopt at your own risk.
This alpha build is intended for internal testing only. Adopt at your own risk.
Changes listed in HISTORY.md.
5.0.0-alpha.0 diff v4.13.0 (2023-01-23)
The MongoDB Node.js team is pleased to announce version 4.17.2 of the mongodb package!
The MongoDB Node.js team is pleased to announce version 4.17.2 of the mongodb package!
When enabling serverApi the driver's RTT mesurment logic (used to determine the closest node) still sent the legacy hello command "isMaster" causing the server to return an error. Unfortunately, the error handling logic did not correctly destroy the socket which would cause a leak.
Both sending the correct hello command and the error handling connection clean up logic are fixed in this change.
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 4.17.1 of the mongodb package!
The MongoDB Node.js team is pleased to announce version 4.17.1 of the mongodb package!
saslprep updated to correct library.Fixes the import of saslprep to be the correct @mongodb-js/saslprep library.
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 4.17.0 of the mongodb package!
The MongoDB Node.js team is pleased to announce version 4.17.0 of the mongodb package!
mongodb-js/saslprep is now installed by defaultUntil v6, the driver included the saslprep package as an optional dependency for SCRAM-SHA-256 authentication. saslprep breaks when bundled with webpack because it attempted to read a file relative to the package location and consequently the driver would throw errors when using SCRAM-SHA-256 if it were bundled.
The driver now depends on mongodb-js/saslprep, a fork of saslprep that can be bundled with webpack because it includes the necessary saslprep data in memory upon loading. This will be installed by default but will only be used if SCRAM-SHA-256 authentication is used.
ConnectionPoolCreatedEventIn order to avoid mistakenly printing credentials the ConnectionPoolCreatedEvent will replace the credentials option with an empty object. The credentials are still accessble via MongoClient options: client.options.credentials.
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 4.16.0 of the mongodb package!
The MongoDB Node.js team is pleased to announce version 4.16.0 of the mongodb package!
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 4.15.0 of the mongodb package!
The MongoDB Node.js team is pleased to announce version 4.15.0 of the mongodb package!
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
NODE-4992: Deprecate methods and options that reference legacy logger
The MongoDB Node.js team is pleased to announce version 4.14.0 of the mongodb package!
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 4.13.0 of the mongodb package!
The MongoDB Node.js team is pleased to announce version 4.13.0 of the mongodb package!
We invite you to try the mongodb driver immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 4.12.1 of the mongodb package!
The MongoDB Node.js team is pleased to announce version 4.12.1 of the mongodb package!
This version includes a fix to a regression in our monitoring logic that could cause process crashing errors that was introduced in v4.12.0.
If you are using v4.12.0 of the Node driver, we strongly encourage you to upgrade.
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
Many thanks to @ImRodry for helping us fix the documentation for our deprecated callback overloads in this release!
The MongoDB Node.js team is pleased to announce version 4.12.0 of the mongodb package!
ChangeStreams are now async iterables and can be used anywhere that expects an async iterable. Notably, change streams can now be used in Javascript for-await loops:
const changeStream = collection.watch();
for await (const change of changeStream) {
console.log(“Received change: “, change);
}
Some users may have been using change streams in for-await loops manually by using a for-await loop with the ChangeStream’s internal cursor. For example:
const changeStream = collection.watch();
for await (const change of changeStream.cursor) {
console.log(“Received change: “, change);
}
The change stream cursor has no support for resumabilty and consequently the change stream will never attempt to resume on any errors. We strongly caution against using a change stream cursor as an async iterable and strongly recommend using the change stream directly.
Version 4.7.0 of the Node driver released an improvement to our server monitoring in FAAS environments by allowing the driver to skip monitoring events if there were more than one monitoring events in the queue when the monitoring code restarted. When skipping monitoring events that contained a topology change, the driver would incorrectly fail to update its view of the topology.
Version 4.12.0 fixes this issue by ensuring that the topology is always updated when monitoring events are processed.
This release also modifies the data structures used internally in the driver to use linked lists in places where random access is not required and constant time insertion and deletion is beneficial.
Many thanks to @ImRodry for helping us fix the documentation for our deprecated callback overloads in this release!
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 4.11.0 of the mongodb package!
The MongoDB Node.js team is pleased to announce version 4.11.0 of the mongodb package!
Version 4.3.0 of the Node driver added Typescript support for dot notation into our Filter type but
in the process it broke support for recursive schemas. In 4.11.0, we now support mutually recursive schemas and
provide type safety on dot notation queries up to a depth of 8. Beyond a depth of 8, code still compiles
but is no longer type checked (it falls back to a type of any).
interface Author {
name: string;
bestBook: Book;
}
interface Book {
title: string;
author: Author;
}
let authors: Collection<Author>
// below a depth of 8, type checking is enforced
authors.findOne({ 'bestBook.author.bestBook.title': 25 }})
// ✅ expected compilation error is thrown: "title must be a string"
// at a depth greater than 8 code compiles but is not type checked (9 deep in this example)
authors.findOne({ 'bestBook.author.bestBook.author.bestBook.author.bestBook.author.name': 25 })
// ⛔️ perhaps unexpected, no compilation error is thrown because the key is too deeply nested
Note that our depth limit is a product of Typescript's recursive type limitations.
If the optional aws-sdk dependency is installed, the driver will now use the SDK to get credentials
from the environment. Because of this, if you have a shared AWS credentials or config file, then
those credentials will be used by default if AWS auth environment variables are not set. To override this
behavior, set AWS_SHARED_CREDENTIALS_FILE="" in your shell or set the
equivalent environment variable value in your script or application. Alternatively, you can create
an AWS profile specifically for your MongoDB credentials and set the AWS_PROFILE environment
variable to that profile name.
Many thanks to those who contributed to this release!
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
In this release you will notice deprecation warnings in doc comments for all our callback overloads and if you are working in VSCode you should notice…
The MongoDB Node.js team is pleased to announce version 4.10.0 of the mongodb package!
Looking to improve our API's consistency and handling of errors we are planning to remove callback support in the next major release of the driver. Today marks the notice of their removal. Migrating to a promise only API allows us to offer uniform error handling and better native support for automatic promise construction. In this release you will notice deprecation warnings in doc comments for all our callback overloads and if you are working in VSCode you should notice ~strikethroughs~ on these APIs. We encourage you to migrate to promises where possible:
async/await syntax can yield the best experience with promise usage.require('util').callbackify(() => collection.findOne())(callback)collection.findOne().then(res => callback(null, res), err => callback(err))While the 4.10.0 version only deprecates our support of callbacks, there will be a major version that removes the support altogether. In order to keep using callbacks after v5 is released, we recommend migrating your driver version to mongodb-legacy (github link). This package wraps every single async API our driver offers and is designed to provide the exact behavior of the MongoDB 4.10.0 release (both callbacks and promises are supported). Any new features added to MongoDB will be automatically inherited but will only support promises. This package is fully tested against our current suite and adoption should be confined to changing an import require('mongodb') -> require('mongodb-legacy'). If this package is useful to you and your use case we encourage you to adopt it before v5 to ensure it continues to work as expected.
Read more about it on the package's readme here:
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 4.9.1 of the mongodb package!
The MongoDB Node.js team is pleased to announce version 4.9.1 of the mongodb package!
This is a bug fix release as noted below.
In fact, it did support it at run time and now the types correctly reflect that, along with the corresponding deprecations we made to the nested write…
The MongoDB Node.js team is pleased to announce version 4.9.0 of the mongodb package!
We have corrected an inconsistency with our writeConcern options in the type definitions where the MongoClient alleged to not support "writeConcern" as an option. In fact, it did support it at run time and now the types correctly reflect that, along with the corresponding deprecations we made to the nested writeConcern config settings.
Our index specification handling had a few peculiar edge cases that we have detailed below, we believe these are unlikely to affect a vast majority of users as the type definitions would have likely reported an error with the impacted usage. As a feature, the typescript definitions now support a javascript Map as a valid input for an index specification.
<details> <summary><strong>Index Specification Detailed Fixes</strong></summary> <br> <ul> <li>Map as a valid input type in TS definition</li> <li>Uses Map under the hood to ensure key order is preserved, fixed numeric index key order issue in combination with FLE usage</li> <li>Tuples passed at the top level to <code>createIndex</code> were incorrectly parsed as string input<ul> <li><code>createIndex(['myKey', 1])</code> would create <code>{ 'myKey': 1, '1': 1 }</code>. </li> <li>Now it's correctly detected if the second arg is one of the known index directions. </li> <li>For complex programmatic generation of indexes we recommend using a Map to avoid all the edge cases here.</li> </ul> </li> <li>Type strictness on this nesting of array (one or more)</li> <li>Type strictness for createIndexes aligned with createIndex<ul> <li>No longer accepts just Document, checks that the values are a known IndexDirection</li> </ul> </li> </ul> </details>
As per usual this release brings in the latest BSON release (v4.7.0) which added automatic UUID support. You can read more about that in the BSON release notes here!
Special thanks to the folks who contributed to this release!
oplogReplay flag support fixoplogReplay option as deprecated (#3337) (6c69b7d)We invite you to try the mongodb library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 4.8.1 of the mongodb package!
The MongoDB Node.js team is pleased to announce version 4.8.1 of the mongodb package!
This patch comes with some bug fixes that are listed below as well as a quality of life improvement for nested keys in the UpdateFilter and Filter types. Thanks to @coyotte508 (#3328) for contributing this improvement!
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 4.8.0 of the mongodb package!
The MongoDB Node.js team is pleased to announce version 4.8.0 of the mongodb package!
Thanks to a contribution from @coyotte508, in this release you will now get auto-complete and type safety for nested keys in an update filter. See the example below:
client.connect() fixupIn our last release we made explicitly calling client.connect() before performing operations optional with some caveats. In this release client.startSession() can now be called before connecting to MongoDB.
NOTES:
- The only APIs that need the client to be connected before using are the legacy
collection.initializeUnorderedBulkOp()/collection.initializeOrderedBulkOp()builder methods. However, the preferredcollection.bulkWrite()API can be used without calling connect explicitly.- While executing operations without explicitly connecting may be streamlined and convenient, depending on your use case
client.connect()could still be useful to find out early if there is some easily detectable issue (ex. networking) that prevents you from accessing your database.
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
All related APIs marked with @expiremental in the documentation. There are no guarantees that the APIs will not undergo breaking changes without prior…
The MongoDB Node.js team is pleased to announce version 4.7.0 of the mongodb package! Happy MongoDB World Day!
zstd compression is now supported by the NodeJS driver. To enable zstd compression, add it as a dependency in your project: npm install –save @mongodb-js/zstd. The add the option to your URI options: mongodb://host:port/db?compressors=zstd.
The Node driver has improved connection storm avoidance by limiting the number of connections that the driver will attempt to open to each server at a time. The number of concurrent connection attempts is set to 2 by default, but can be configured with a new MongoClient argument, maxConnecting. The following code example creates a new MongoClient that configures maxConnecting to 5.
const client = new MongoClient('MONGODB_URL', { maxConnecting: 5 });
The collection.watch function now supports a new option, showExpandedEvents. When showExpandedEvents is enabled, change streams will report the following events on servers 6.0 and later:
createIndexesdropIndexesmodifycreateshardCollectionOn servers 6.1.0 and later, showExpandedEvents will also show change stream events for the following commands:
reshardCollectionrefineCollectionShardKeyAs an example, the following code creates a change stream that has expanded events enabled on a collection:
const client = new MongoClient('MONGODB_URL');
await client.connect();
const collection = client.db('example-db').collection('example-collection');
const changeStream = collection.watch([], { showExpandedEvents: true });
Change streams now support pre and post images for update events. To enable pre and post images, the collection must be created with the changeStreamPreAndPostImages option enabled:
const collection = await db.createCollection(‘collectionName’, { changeStreamPreAndPostImages: { enabled: true }} )
Pre and post images can then be enabled on the change stream when the change stream is created:
const changeStream = collection.watch([], { fullDocumentBeforeChange: ‘required’ })
See the documentation on pre and post images for more information: https://www.mongodb.com/docs/v6.0/changeStreams/#change-streams-with-document-pre--and-post-images.
The driver now only processes the most recent server monitoring event if multiple heartbeat events are recorded in sequence before any can be processed. In serverless environments, this results in increased performance when a function is invoked after a period of inactivity as well as lower resource consumption.
The 5.0 server compatible release unintentionally broke the estimatedDocumentCount command on views by changing the implementation from the count command to aggregate and a collStats stage. This release fixes estimatedDocumentCount on views by reverting the implementation to use count.
Due to an oversight, the count command was omitted from the Stable API in server versions 5.0.0 - 5.0.8 and 5.1.0 - 5.3.1, so users of the Stable API with estimatedDocumentCount are recommended to upgrade their MongoDB clusters to 5.0.9 or 5.3.2 (if on Atlas) or set apiStrict: false when constructing their MongoClients.
If an operation is run before MongoClient.connect is called by the client, the driver will now automatically connect along with that first operation. This makes the repl experience much more streamlined, going right from client construction to your first insert or find. However, MongoClient.connect can still be called manually and remains useful for learning about misconfiguration (auth, server not started, connection string correctness) early in your application's startup.
Note: It's a known limitation that explicit sessions (client.startSession) and
initializeOrderedBulkOp,initializeUnorderedBulkOpcannot be used until MongoClient.connect is first called. Look forward to a future patch release that will correct these inconsistencies.
Clustered Collections can now be created using the createCollection method in the Node driver:
const client = new MongoClient('MONGODB_URL');
// No need to connect anymore! (see above)
const collection = await client.db(‘example-db’).createCollection(‘example-collection’, {
key: _id,
unique: true
});
More information about clustered indexes can be found on the official documentation page. https://www.mongodb.com/docs/upcoming/core/clustered-collections/
To enable the driver to use the new Automatic Encryption Shared Library instead of using mongocryptd, pass the location of the library in the auto-encryption extra options to the MongoClient. Example:
const client = new MongoClient(uri, {
autoEncryption: {
keyVaultNamespace: 'encryption.__keyVault',
kmsProviders: {
local: { key: 'localKey' }
},
extraOptions: {
cryptSharedLibPath: "/path/to/mongo_crypt_v1.dylib",
},
encryptedFieldsMap: {
"default.secretCollection": {
[
{
keyId: '_id',
path: 'ssn',
bsonType: 'string',
queries: { queryType: 'equality' }
}
]
},
},
},
})
Queryable Encryption is a beta feature that enables you to encrypt data in your application before you send it over the network to MongoDB while still maintaining the ability to query the encrypted data. With Queryable Encryption enabled, no MongoDB-managed service has access to your data in an unencrypted form.
Checkout the documentation: https://www.mongodb.com/docs/upcoming/core/queryable-encryption/queryable-encryption/
ATTENTION: This feature is included in this release as a beta preview. All related APIs marked with
@expirementalin the documentation. There are no guarantees that the APIs will not undergo breaking changes without prior notice.
Features:
Bug Fixes
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 4.6.0 of the mongodb package!
The MongoDB Node.js team is pleased to announce version 4.6.0 of the mongodb package!
Our change stream document type and watch API have undergone some improvements! You can now define your own custom type for the top level document returned in a 'change' event. This is very useful when using a pipeline that significantly changes the shape of the change document (ex. $replaceRoot, $project operators). Additionally, we've improved the type information of the default change stream document to default to union of the possible events from MongoDB. This works well with typescript's ability to narrow a Discriminated Union based on the operationType key in the default change stream document.
Prior to this change the ChangeStreamDocument inaccurately reflected the runtime shape of the change document. Now, using the union, we correctly indicate that some properties do not exist at all on certain events (as opposed to being optional). With this typescript fix we have added the properties to for rename events, as well as lsid, txnNumber, and clusterTime if the change is from within a transaction.
NOTE: Updating to this version may require fixing typescript issues. Those looking to adopt this version but defer any type corrections can use the watch API like so: .watch<any, X>(). Where X controls the type of the change document for your use case.
Check out the examples and documentation here.
Operations will now be directed towards servers that have fewer in progress operations. This distributes load across servers and prevents overwhelming servers that are already under load with additional requests.
This release includes some experimental features that are not yet ready for use. As a reminder, anything marked experimental is not a part of the official driver API and is subject to change without notice.
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version v4.6.0-alpha.0 of the mongodb package!
The MongoDB Node.js team is pleased to announce version v4.6.0-alpha.0 of the mongodb package!
This release is for internal testing - NOT intended for use production.
The MongoDB Node.js team is pleased to announce version 4.5.0 of the mongodb package!
The MongoDB Node.js team is pleased to announce version 4.5.0 of the mongodb package!
This release includes a number of enhancements noted below.
comment option supportThe comment option is now widely available: by setting a comment on an operation you can trace its value in database logs for more insights.
collection.insertOne(
{ name: 'spot' },
{ comment: { started: new Date() } }
)
An example of a log line, trimmed for brevity. We can see the timestamp of the log and the time created on our client application differ.
{
"t": { "$date": "2022-04-04T16:08:56.079-04:00" },
"attr": {
"commandArgs": {
"documents": [ { "_id": "...", "name": "spot" } ],
"comment": { "started": { "$date": "2022-04-04T20:08:56.072Z" } } }
}
}
This release includes a fix for serverless environments where transient serverHeartBeatFailure events that could be corrected to serverHeartBeatSucceeded events in the next tick of the event loop were nonetheless handled as an actual issue with the client's connection and caused unnecessary resource clean up routines.
It turns out that since Node.js handles timeout events first in the event loop, socket timeouts expire while the FaaS environment is dormant and the timeout handler code is the first thing that runs upon function wake prior to checking for any data from the server. Delaying the timeout handling until after the data reading phase avoids the sleep-induced timeout error in the cases where the connection is still healthy.
Typescript 4.7 may not be out yet but in preparation for its release we've fixed issues compiling against that version. The main new obstacle was defaulting generic arguments that require that the constraining condition enforce similarity with the defaulted type. You may notice that our change stream watch<T extends Document = Document>() methods now requires that T extends Document, a requirement that already had to be met by the underlying ChangeStreamDocument type.
comment field (#3167) (4e2f9bf)watch type parameter to extend ChangeStream type parameter (#3183) (43ba9fc)We invite you to try the mongodb library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 4.4.1 of the mongodb package!
The MongoDB Node.js team is pleased to announce version 4.4.1 of the mongodb package!
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
In the 4.0.0 release of the driver, the deprecated collection.count() method was inadvertently changed to behave like collection.countDocuments(). In…
The MongoDB Node.js team is pleased to announce version 4.4.0 of the mongodb package!
This release includes a few new features described below.
KMIP can now be configured as a KMS provider for CSFLE by providing the KMIP endpoint in the kmsProviders option.
Example:
new MongoClient(uri, { autoEncryption: { kmsProviders: { kmip: { endpoint: 'host:port' }}}})
Custom TLS options can now be provided for connection to the KMS servers on a per KMS provider basis.
Example:
new MongoClient(uri, { autoEncryption: { tlsOptions: { aws: { tlsCAFile: 'path/to/file' }}}})
Valid options are tlsCAFile, tlsCertificateKeyFile, tlsCertificateKeyFilePassword and all accept strings as values: a string path to a certificate location on the file system or a string password.
Hostname canonicalization when using GSSAPI authentication now accepts 'none', 'forward', and 'forwardAndReverse' as auth mechanism properties. 'none' will perform no canonicalization (default), 'forward' will perform a forward cname lookup, and 'forwardAndReverse' will perform a forward lookup followed by a reverse PTR lookup on the IP address. Previous boolean values are still accepted and map to false -> 'none' and true -> 'forwardAndReverse'.
Example:
new MongoClient('mongodb://user:pass@host:port/db?authMechanism=GSSAPI&authMechanismProperties=CANONICALIZE_HOST_NAME=forward');
For cases when the service host name differs from the connection’s host name (most likely when creating new users on localhost), a SERVICE_HOST auth mechanism property may now be provided.
Example:
new MongoClient('mongodb://user:pass@host:port/db?authMechanism=GSSAPI&authMechanismProperties=SERVICE_HOST:example.com')
In the 4.0.0 release of the driver, the deprecated collection.count() method was inadvertently changed to behave like collection.countDocuments(). In this release, we have updated the collection.count() behavior to match the legacy behavior:
collection.count will behave the same as collection.countDocuments and perform a collection scan.collection.count will behave the same as collection.estimatedDocumentCount and rely on collection metadata.We also deprecated the cursor.count() method and will remove it in the next major version along with collection.count(); please use collection.estimatedDocumentCount() or collection.countDocuments() instead.
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 4.3.1 of the mongodb package!
The MongoDB Node.js team is pleased to announce version 4.3.1 of the mongodb package!
In this patch release, we address the limitation introduced in 4.3.0 with the dot notation Typescript improvements and recursive types.
Namely, this fix removes compilation errors for self-referential types.
Note that this fix still has the following limitations:
any after the first level of recursion for self-referential typesinterface Node {
next: Node | null;
}
declare const collection: Collection<Node>;
// no error here even though `next` is of type `Node | null`
collection.find({
next: {
next: 'asdf'
}
});
interface A {
b: B;
}
interface B {
a: A;
}
declare const mutuallyRecursive: Collection<A>;
// this will throw an error because there is indirect recursion
// between types (A depends on B which depends on A and so on)
mutuallyRecursive.find({});
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 4.3.0 of the mongodb package!
The MongoDB Node.js team is pleased to announce version 4.3.0 of the mongodb package!
This release includes SOCKS5 support and a couple of other important features and bug fixes that we hope will improve your experience with the node driver.
The SOCKS5 options can be configured via the proxyHost, proxyPort, proxyPassword and proxyUsername options in the connection string passed to the MongoClient instance. Big thanks to @addaleax for helping with this feature!
The other notable features address performance and TypeScript as detailed below.
The original release of the 4.x driver relied on a new version of the BSON library that enables UTF-8 validation by default, resulting in noticeable performance degradation over the 3.x driver when processing over string data. This release introduces an option to opt out of this validation by specifying enableUtf8Validation: false at the client, database, collection, or individual operation level.
For example:
// disable UTF-8 validation globally on the MongoDB client
const client = new MongoClient('mongodb://localhost:27017', { enableUtf8Validation: false });
// disable UTF-8 validation for a particular operation
const client = new MongoClient('mongodb://localhost:27017');
const db = client.db('database name');
const collection = db.collection('collection name');
await collection.find({ name: 'John Doe'}, { enableUtf8Validation: false });
Thanks to an amazing contribution from @avaly we now have support for key auto-completion and type hinting on nested documents! MongoDB permits using dotted keys to reference nested keys or specific array indexes within your documents as a shorthand for getting at keys beneath the top layer. Typescript's Template Literal types allow us to take the interface defined on a collection and calculate at compile time the nested keys and indexes available.
For example:
interface Human {
name: string;
age: number;
}
interface Pet {
name: string
bestFriend: Human
}
const pets = client.db().collection<Pet>('pets');
await pets.findOne({ 'bestFriend.age': 'young!' }) // typescript error!
Here's what autocomplete suggests in VSCode: <img width="171" alt="Screen Shot 2022-01-06 at 5 29 17 PM" src="https://user-images.githubusercontent.com/81593090/148467749-ba4698fd-8a57-4656-ac5e-f02acf52d90f.png">
WARNING: There is a known shortcoming to this feature: recursive types can no longer be used in your schema. For example, an interface that references itself or references another schema that references back to the root schema cannot be used on our Collection generic argument. Unlike at runtime where a "recursive" shaped document has an eventual stopping point we don't have the tools within the language to declare a base case enumerating nested keys. We hope this does not cause friction when upgrading driver versions: please do not hesitate to reach out with any feedback you have about this feature.
We have also enhanced the type inference for the _id type. Now, when performing operations on a collection, the following holds true based on the type of the schema:
_id is specified on the schema, it is inferred to be of type ObjectId and is optional on inserts._id is specified on the schema as required, then the _id type is inferred to be of the specified type and is required on inserts._id is specified on the schema as optional, it is inferred to be of the specified type and is optional on inserts: this format is intended to be used with the pkFactory option in order to ensure a consistent _id is assigned to every new document.enableUtf8Validation option (#3074) (4f56409)GridFSBucketWriteStream.prototype.end() return this for compat with @types/node@17.0.6 (#3088) (7bb9e37)We invite you to try the mongodb library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 4.2.2 of the mongodb package!
The MongoDB Node.js team is pleased to announce version 4.2.2 of the mongodb package!
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
Your coding agent can read these notes before it upgrades. Set up the MCP server →