The official MongoDB Node.js driver
APACHE-2.0 License
Bot releases are hidden (Show)
Published by nbbeeken about 2 years ago
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.
Published by nbbeeken over 2 years ago
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.
Published by baileympearson over 2 years ago
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:
createIndexes
dropIndexes
modify
create
shardCollection
On servers 6.1.0 and later, showExpandedEvents
will also show change stream events for the following commands:
reshardCollection
refineCollectionShardKey
As 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
,initializeUnorderedBulkOp
cannot 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
@expiremental
in 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.
Published by baileympearson over 2 years ago
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.
Published by baileympearson over 2 years ago
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.
Published by nbbeeken over 2 years ago
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.
Published by nbbeeken over 2 years ago
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.
Published by dariakp over 2 years ago
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.
Published by baileympearson almost 3 years ago
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.
Published by dariakp almost 3 years ago
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:
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/[email protected] (#3088) (7bb9e37)We invite you to try the mongodb library immediately, and report any issues to the NODE project.
Published by nbbeeken almost 3 years ago
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.
Published by nbbeeken almost 3 years ago
The MongoDB Node.js team is pleased to announce version 4.2.1 of the mongodb package!
This release fixes an issue with the dbName being overridden by the authSource option. Additionally, we have ensured that cursors re-run server selection when fetching additional batches, which should reduce issues encountered in long running function as a service environments.
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
Published by nbbeeken almost 3 years ago
This release includes a number of features we’re happy to announce. You can now run aggregation pipelines that write write to a MongoDB collection using $out and $merge stages on secondaries! We’ve added an option to limit the number of hosts the driver will connect to when using SRV DNS lookups to manage your host addresses. And lastly, the authorizedCollection
option is now usable on the db.listCollections()
function.
Additionally, in this release, we’ve marked collection.mapReduce()
as deprecated. The same functionality can be replicated in the much more flexible aggregation pipeline. Visit Map-Reduce to Aggregation Pipeline to learn more.
The minimum supported MongoDB version is 3.6. Attempts to connect to a MongoDB server older than 3.6 will result in an error.
Please take note of the MongoDB Software Lifecycle Schedules for timeframes of supported server versions.
authorizedCollections
option to the db.listCollections
method (#3021) (e1234a7)defaultTransactionOptions
with POJO rather than ReadConcern instance (#3032) (53b3164)We invite you to try the mongodb library immediately, and report any issues to the NODE project.
Published by dariakp almost 3 years ago
This release includes a couple of bug fixes as noted below:
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
Published by nbbeeken about 3 years ago
The MongoDB Node.js team is pleased to announce version 3.7.3 of the mongodb package!
Full Changelog: https://github.com/mongodb/node-mongodb-native/compare/v3.7.2...v3.7.3
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
Published by dariakp about 3 years ago
The MongoDB Node.js team is pleased to announce version 3.7.2 of the mongodb package!
This release contains a fix for optional require of dependencies on yarn berry.
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
Published by dariakp about 3 years ago
The MongoDB Node.js team is pleased to announce version 4.1.3 of the mongodb package!
This release includes a couple of TypeScript fixes as noted below:
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
Published by nbbeeken about 3 years ago
The MongoDB Node.js team is pleased to announce version 4.1.2 of the mongodb package!
This release addresses a number of bug fixes, please peruse the list below for more information on each fix.
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
Published by nbbeeken about 3 years ago
The MongoDB Node.js team is pleased to announce version 3.7.1 of the mongodb package!
This release contains an internal improvement that makes our monitor utilize the new hello handshake for monitoring when available.
We invite you to try the mongodb library immediately, and report any issues to the NODE project.
Published by nbbeeken about 3 years ago
The MongoDB Node.js team is pleased to announce version 3.7.0 of the mongodb package!
Versioned API is a new feature in MongoDB 5.0 that allows user-selectable API versions, subsets of MongoDB server semantics, to be declared on a client. During communication with a server, clients with a declared API version will force the server to behave in a manner compatible with the API version. Declaring an API version on a client can be used to ensure consistent responses from a server, providing long term API stability for an application. The declared API version is applied to all commands run through the client, including those sent through the generic RunCommand helper. Specifying versioned API options in the command document AND declaring an API version on the client is not supported and will lead to undefined behavior.
// Declare API version "1" for the client
client = new MongoClient(uri, { serverApi: { version: '1' } });
cursor = client.db('database').collection('coll').find(...);
Declaring a strict
API version will cause the MongoDB server to reject all commands that are not part of the declared API version. This includes command options and aggregation pipeline stages. For example, the following find
call would fail because the tailable
option is not part of version 1:
// Declare API version "1" for the client, with strict on
client = new MongoClient(uri, { serverApi: { version: '1', strict: true } });
// Fails with an error
cursor = client.db('database').collection('coll').find({ ... }, { tailable: true });
The deprecationErrors
option can be used to enable command failures when using functionality that is deprecated from version 1. Note that at the time of this writing, no deprecations in version 1 exist.
// Declare API version "1" for the client, with deprecationErrors on
client = new MongoClient(uri, { serverApi: { version: '1', deprecationErrors: true } });
// Note: since API version "1" is the initial version, there are no deprecated commands to provide as an example yet.
We invite you to try the mongodb library immediately, and report any issues to the NODE project.