The Official MongoDB Node.js Driver

Overview

MongoDB NodeJS Driver

npm

The official MongoDB driver for Node.js.

NOTE: v3.x released with breaking API changes. You can find a list of changes here.

Version 4.0

Looking for the latest? We're working on the next major version of the driver, now in beta. Check out our beta version 4.0 here, which includes a full migration of the driver to TypeScript.

Quick Links

what where
documentation http://mongodb.github.io/node-mongodb-native
api-doc http://mongodb.github.io/node-mongodb-native/3.6/api
source https://github.com/mongodb/node-mongodb-native
mongodb http://www.mongodb.org

Bugs / Feature Requests

Think you’ve found a bug? Want to see a new feature in node-mongodb-native? Please open a case in our issue management tool, JIRA:

  • Create an account and login jira.mongodb.org.
  • Navigate to the NODE project jira.mongodb.org/browse/NODE.
  • Click Create Issue - Please provide as much information as possible about the issue type and how to reproduce it.

Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the Core Server (i.e. SERVER) project are public.

Support / Feedback

For issues with, questions about, or feedback for the Node.js driver, please look into our support channels. Please do not email any of the driver developers directly with issues or questions - you're more likely to get an answer on the MongoDB Community Forums.

Change Log

Change history can be found in HISTORY.md.

Compatibility

For version compatibility matrices, please refer to the following links:

Installation

The recommended way to get started using the Node.js driver is by using npm (Node Package Manager) to install the dependency in your project.

MongoDB Driver

Given that you have created your own project using npm init we install the MongoDB driver and its dependencies by executing the following npm command.

npm install mongodb --save

This will download the MongoDB driver and add a dependency entry in your package.json file.

You can also use the Yarn package manager.

Troubleshooting

The MongoDB driver depends on several other packages. These are:

The kerberos package is a C++ extension that requires a build environment to be installed on your system. You must be able to build Node.js itself in order to compile and install the kerberos module. Furthermore, the kerberos module requires the MIT Kerberos package to correctly compile on UNIX operating systems. Consult your UNIX operation system package manager for what libraries to install.

Windows already contains the SSPI API used for Kerberos authentication. However, you will need to install a full compiler tool chain using Visual Studio C++ to correctly install the Kerberos extension.

Diagnosing on UNIX

If you don’t have the build-essentials, this module won’t build. In the case of Linux, you will need gcc, g++, Node.js with all the headers and Python. The easiest way to figure out what’s missing is by trying to build the Kerberos project. You can do this by performing the following steps.

git clone https://github.com/mongodb-js/kerberos
cd kerberos
npm install

If all the steps complete, you have the right toolchain installed. If you get the error "node-gyp not found," you need to install node-gyp globally:

npm install -g node-gyp

If it correctly compiles and runs the tests you are golden. We can now try to install the mongod driver by performing the following command.

cd yourproject
npm install mongodb --save

If it still fails the next step is to examine the npm log. Rerun the command but in this case in verbose mode.

npm --loglevel verbose install mongodb

This will print out all the steps npm is performing while trying to install the module.

Diagnosing on Windows

A compiler tool chain known to work for compiling kerberos on Windows is the following.

  • Visual Studio C++ 2010 (do not use higher versions)
  • Windows 7 64bit SDK
  • Python 2.7 or higher

Open the Visual Studio command prompt. Ensure node.exe is in your path and install node-gyp.

npm install -g node-gyp

Next, you will have to build the project manually to test it. Clone the repo, install dependencies and rebuild:

git clone https://github.com/christkv/kerberos.git
cd kerberos
npm install
node-gyp rebuild

This should rebuild the driver successfully if you have everything set up correctly.

Other possible issues

Your Python installation might be hosed making gyp break. Test your deployment environment first by trying to build Node.js itself on the server in question, as this should unearth any issues with broken packages (and there are a lot of broken packages out there).

Another tip is to ensure your user has write permission to wherever the Node.js modules are being installed.

Quick Start

This guide will show you how to set up a simple application using Node.js and MongoDB. Its scope is only how to set up the driver and perform the simple CRUD operations. For more in-depth coverage, see the tutorials.

Create the package.json file

First, create a directory where your application will live.

mkdir myproject
cd myproject

Enter the following command and answer the questions to create the initial structure for your new project:

npm init

Next, install the driver dependency.

npm install mongodb --save

You should see NPM download a lot of files. Once it's done you'll find all the downloaded packages under the node_modules directory.

Start a MongoDB Server

For complete MongoDB installation instructions, see the manual.

  1. Download the right MongoDB version from MongoDB
  2. Create a database directory (in this case under /data).
  3. Install and start a mongod process.
mongod --dbpath=/data

You should see the mongod process start up and print some status information.

Connect to MongoDB

Create a new app.js file and add the following code to try out some basic CRUD operations using the MongoDB driver.

Add code to connect to the server and the database myproject:

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'myproject';
const client = new MongoClient(url);
// Use connect method to connect to the server
client.connect(function(err) {
  assert.equal(null, err);
  console.log('Connected successfully to server');

  const db = client.db(dbName);

  client.close();
});

Run your app from the command line with:

node app.js

The application should print Connected successfully to server to the console.

Insert a Document

Add to app.js the following function which uses the insertMany method to add three documents to the documents collection.

const insertDocuments = function(db, callback) {
  // Get the documents collection
  const collection = db.collection('documents');
  // Insert some documents
  collection.insertMany([{ a: 1 }, { a: 2 }, { a: 3 }], function(err, result) {
    assert.equal(err, null);
    assert.equal(3, result.result.n);
    assert.equal(3, result.ops.length);
    console.log('Inserted 3 documents into the collection');
    callback(result);
  });
};

The insert command returns an object with the following fields:

  • result Contains the result document from MongoDB
  • ops Contains the documents inserted with added _id fields
  • connection Contains the connection used to perform the insert

Add the following code to call the insertDocuments function:

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'myproject';

// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
  assert.equal(null, err);
  console.log('Connected successfully to server');

  const db = client.db(dbName);

  insertDocuments(db, function() {
    client.close();
  });
});

Run the updated app.js file:

node app.js

The operation returns the following output:

Connected successfully to server
Inserted 3 documents into the collection

Find All Documents

Add a query that returns all the documents.

const findDocuments = function(db, callback) {
  // Get the documents collection
  const collection = db.collection('documents');
  // Find some documents
  collection.find({}).toArray(function(err, docs) {
    assert.equal(err, null);
    console.log('Found the following records');
    console.log(docs);
    callback(docs);
  });
};

This query returns all the documents in the documents collection. Add the findDocument method to the MongoClient.connect callback:

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'myproject';

// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
  assert.equal(null, err);
  console.log('Connected correctly to server');

  const db = client.db(dbName);

  insertDocuments(db, function() {
    findDocuments(db, function() {
      client.close();
    });
  });
});

Find Documents with a Query Filter

Add a query filter to find only documents which meet the query criteria.

const findDocuments = function(db, callback) {
  // Get the documents collection
  const collection = db.collection('documents');
  // Find some documents
  collection.find({ a: 3 }).toArray(function(err, docs) {
    assert.equal(err, null);
    console.log('Found the following records');
    console.log(docs);
    callback(docs);
  });
};

Only the documents which match 'a' : 3 should be returned.

Update a document

The following operation updates a document in the documents collection.

const updateDocument = function(db, callback) {
  // Get the documents collection
  const collection = db.collection('documents');
  // Update document where a is 2, set b equal to 1
  collection.updateOne({ a: 2 }, { $set: { b: 1 } }, function(err, result) {
    assert.equal(err, null);
    assert.equal(1, result.result.n);
    console.log('Updated the document with the field a equal to 2');
    callback(result);
  });
};

The method updates the first document where the field a is equal to 2 by adding a new field b to the document set to 1. Next, update the callback function from MongoClient.connect to include the update method.

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'myproject';

// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
  assert.equal(null, err);
  console.log('Connected successfully to server');

  const db = client.db(dbName);

  insertDocuments(db, function() {
    updateDocument(db, function() {
      client.close();
    });
  });
});

Remove a document

Remove the document where the field a is equal to 3.

const removeDocument = function(db, callback) {
  // Get the documents collection
  const collection = db.collection('documents');
  // Delete document where a is 3
  collection.deleteOne({ a: 3 }, function(err, result) {
    assert.equal(err, null);
    assert.equal(1, result.result.n);
    console.log('Removed the document with the field a equal to 3');
    callback(result);
  });
};

Add the new method to the MongoClient.connect callback function.

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'myproject';

// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
  assert.equal(null, err);
  console.log('Connected successfully to server');

  const db = client.db(dbName);

  insertDocuments(db, function() {
    updateDocument(db, function() {
      removeDocument(db, function() {
        client.close();
      });
    });
  });
});

Index a Collection

Indexes can improve your application's performance. The following function creates an index on the a field in the documents collection.

const indexCollection = function(db, callback) {
  db.collection('documents').createIndex({ a: 1 }, null, function(err, results) {
    console.log(results);
    callback();
  });
};

Add the indexCollection method to your app:

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://localhost:27017';

const dbName = 'myproject';

// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
  assert.equal(null, err);
  console.log('Connected successfully to server');

  const db = client.db(dbName);

  insertDocuments(db, function() {
    indexCollection(db, function() {
      client.close();
    });
  });
});

For more detailed information, see the tutorials.

Next Steps

License

Apache 2.0

© 2009-2012 Christian Amor Kvalheim © 2012-present MongoDB Contributors

Comments
  • feat(collection): add colleciton level document mapping/unmapping

    feat(collection): add colleciton level document mapping/unmapping

    This is a WIP to add mapping / unmapping on a collection level.

    This can give document-mapper libraries a quicker way to map documents so that they don't have to wrap every collection's methods. (i.e. type-mongo-mapper)

    Features to be implemented:

    • Mapping: Allow all collection methods that return plain documents (ignoring aggregations) to be "mapped" (i.e. converting a document to a class).
    • Unmapping: Allow all collection methods that insert or update plain documents (without update modifiers) to be unmapped (i.e. converting a class to a document).

    Basic Example:

    class User {
        public _id;
        public firstName;
        public lastName;
        public createdAt;
    
        constructor(doc) {
            this._id = doc._id || new ObjectID();
            this.firstName = doc.firstName;
            this.lastName = doc.lastName;
            this.createdAt = doc.createdAt || new Date();
        }
    
        get id() {
            return this._id.toString();
        }
    
        get fullName() {
            return `${this.firstName} ${this.lastName}`;
        }
    }
    
    const collection = db.collection('users', {
        map: (doc) => new User(doc),
        unmap: (user) => ({
            _id: user._id,
            firstName: doc.firstName,
            lastName: doc.lastName,
            createdAt: doc.createdAt,
        })
    });
    
    const user = await collection.findOne({ /* ... */ });
    assert.true(user instanceof User); // true
    
    const cursor = await collection.find({ /* ... */ }).toArray();
    assert.true(user[0] instanceof User); // true
    
    const { ok, value } = await collection.findOneAndUpdate({ /* ... */ });
    assert.true(value instanceof User); // true
    
    const user = new User({ firstName: 'John', lastName: 'Doe' });
    await collection.insertOne(user); // calls unmap option.. createdAt & the ID were created on the constructor, so it'd already exist.
    

    Discussion: https://jira.mongodb.org/projects/NODE/issues/NODE-1450?filter=allissues Related: https://github.com/mongodb/js-bson/issues/211

    Also, my heart wants this to belong in the bson library, but right now BSON serialization seems to be handed over any javascript object instead of just the documents, so it's (de)serializing more than it should? (I'm unsure of how the internals work exactly). I know the C# BSON driver has advanced class mapping, so that's what made me believe this type of thing can go there. And I believe the serialization option above can be done through a toBSON() function on the class., but it'd still be nice to be more explicit on the collection level and let mapping libraries handle it for you.

    opened by j 22
  • refactor(NODE-3402): implement MongoAPIError and its children

    refactor(NODE-3402): implement MongoAPIError and its children

    Description

    Implement the errors detailed in docs/errors.md from NODE-3363 that fall under MongoAPIError

    What changed? Replacing MongoDriverError instances with the following errors where appropriate

    • MongoInvalidArgumentError
    • MongoMissingDependencyError
    • MongoMissingCredentialsError
    • MongoCompatibilityError
    Team Review 
    opened by W-A-James 21
  • feat(NODE-3589): support dot-notation attributes in Filter

    feat(NODE-3589): support dot-notation attributes in Filter

    Description

    Currently, dot-notation attributes (e.g. foo.bar) in filter objects do not get any type checks.

    What changed?

    This PR changes the implementation of the Filter type to also support dot-notation attributes inside nested objects.

    This PR requires TypeScript >= 4.1, because it relies on template literal types (see: https://github.com/microsoft/TypeScript/pull/40336)

    tracked-in-jira Team Review External Submission 
    opened by avaly 19
  • Queue multiple open connection callbacks

    Queue multiple open connection callbacks

    Hi!

    Since the latest version of node-mongodb-native isn't allowing multiple opened connections, some third-party code might have broken.

    This patch provides backwards compatibility. When someone tries to open a connection more than once, his callback will nevertheless be executed, even if the connection is remaining single.

    Emission of open event is also included for convenient subscription.

    Thanks!

    opened by katspaugh 15
  • GridFS stream support for cancelling upload streams and download streams

    GridFS stream support for cancelling upload streams and download streams

    opened by vkarpov15 14
  • Added support for unavailable replica servers

    Added support for unavailable replica servers

    3 fixes for a ping strategy.

    1. Implemented support for unavailable replica servers
    2. No more lowest.runtimeStats.pingMs = undefined
    3. Configurable options for ping timeout/interval.
    opened by vaseker 14
  • fix(connect): connect with family 0 instead of family 4

    fix(connect): connect with family 0 instead of family 4

    This is a fix for a hard-to-reproduce bug that occurs in certain network setups on Windows 10. In those cases, attempting an IPv6 lookup with a shortname will somehow cause the subsequent IPv4 lookup to also fail, even though it can succeed independently. For some reason, this does NOT happen with family: 0.

    This really should be fixed in either Node or in Windows itself, but since we cannot create a stable reproducer, we will use this fix short-term while we come up with a more stable solution.

    Fixes NODE-1747 Fixes NODE-2143

    Description

    What changed?

    Are there any files to ignore?

    opened by daprahamian 13
  • allow auth option

    allow auth option

    Based on my reading of url_parser.js looks like there's no reason why auth isn't a supported option. Having support for this option would be very helpful for issues like https://github.com/Automattic/mongoose/issues/5419, otherwise we'd have to mutate the user-provided URI or ask users to not use those options anymore.

    opened by vkarpov15 13
  • fix(NODE-3803): Fix _id typing on collection create operations

    fix(NODE-3803): Fix _id typing on collection create operations

    Description

    This PR improves type inference around the _id fields for schemas used by the Collection class.

    What is changing?

    This PR updates the type inference that extracts the type of the _id field from schemas to

    • be easier to understand
    • correctly handle the case where an optional _id is passed in

    See https://jira.mongodb.org/browse/NODE-3761.

    This PR also updates the parameter types for write operations on the collection class to match the following behavior (discussed in this slack thread)

    • _id not defined on collection means the default ObjectId will be used, and won't be required on inserts;
    • _id defined as required on a collection means that the user will provide the _id on every insert
    • _id defined as optional means that the user is expecting to rely on a pkFactory method to generate a consistent id
    Is there new documentation needed for these changes?

    Yes (I think)

    What is the motivation for this change?

    Improved typing of the _id field on schemas results in a better developer experience for typescript consumers of the node driver.

    Double check the following

    • [x] Ran npm run check:lint script
    • [x] Self-review completed using the steps outlined here
    • [x] PR title follows the correct format: <type>(NODE-xxxx)<!>: <description>
    • [x] Changes are covered by tests
    Team Review 
    opened by baileympearson 12
  • Refactor

    Refactor

    Hey Christian,

    I'm going around refactoring various parts of this great driver, things like removing dead require statements, variables, functions, etc, adding documentation, splitting out some constructors into their own modules, removing some slow string methods etc etc.

    This has been rebased against your current master branch and I've been taking care to keep the tests working identically to master (btw, they currently fail).

    Take a look and let me know what you think. I do plan on continuing to refactor more as I have time.

    Thanks, Aaron

    opened by aheckmann 12
  • fix(NODE-4423): better type support for nested objects in query & update

    fix(NODE-4423): better type support for nested objects in query & update

    Description

    What is changing?

    Better typing for update & query

    Is there new documentation needed for these changes?

    What is the motivation for this change?

    	interface User {
    		pet: {
    			name: {
    				first: string;
    				last: string;
    			};
    		};
    	}
    	
    	// This works when it shouldn't
    	const query: mongodb.Filter<User> = { "pet.name": { first: 1 } };
    	// This doesn't work when it should
    	const update: mongodb.UpdateFilter<User> = { $set: { "pet.name": { first: "a", last: "b" } } };
    

    The second error is a regression. This PR fixes both issues

    Tickets:

    • https://jira.mongodb.org/browse/NODE-4423
    • https://jira.mongodb.org/browse/NODE-4450 (duplicate)

    Double check the following

    • [x] Ran npm run check:lint script
    • [x] Self-review completed using the steps outlined here
    • [x] PR title follows the correct format: <type>(NODE-xxxx)<!>: <description>
    • [x] Changes are covered by tests
    • [x] New TODOs have a related JIRA ticket
    Team Review External Submission 
    opened by coyotte508 11
  • test(NODE-4918): import all driver APIs from one registry file

    test(NODE-4918): import all driver APIs from one registry file

    Description

    What is changing?

    Is there new documentation needed for these changes?

    What is the motivation for this change?

    Double check the following

    • [ ] Ran npm run check:lint script
    • [ ] Self-review completed using the steps outlined here
    • [ ] PR title follows the correct format: type(NODE-xxxx)[!]: description
      • Example: feat(NODE-1234)!: rewriting everything in coffeescript
    • [ ] Changes are covered by tests
    • [ ] New TODOs have a related JIRA ticket
    opened by nbbeeken 0
  • feat(NODE-4648)!: remove collection insert, update, remove methods

    feat(NODE-4648)!: remove collection insert, update, remove methods

    Description

    What is changing?

    Removes the legacy crud methods.

    What is the motivation for this change?

    Modernize code base, remove duplicate code.

    Double check the following

    TODO:

    • [ ] Migration guide
    • [ ] Feedback on shimming old methods

    • [ ] Ran npm run check:lint script
    • [ ] Self-review completed using the steps outlined here
    • [ ] PR title follows the correct format: type(NODE-xxxx)[!]: description
      • Example: feat(NODE-1234)!: rewriting everything in coffeescript
    • [ ] Changes are covered by tests
    • [ ] New TODOs have a related JIRA ticket
    opened by nbbeeken 1
  • [WIP] feat(NODE-4522)!: remove callback support

    [WIP] feat(NODE-4522)!: remove callback support

    Description

    What is changing?

    Is there new documentation needed for these changes?

    What is the motivation for this change?

    Double check the following

    • [ ] Ran npm run check:lint script
    • [ ] Self-review completed using the steps outlined here
    • [ ] PR title follows the correct format: type(NODE-xxxx)[!]: description
      • Example: feat(NODE-1234)!: rewriting everything in coffeescript
    • [ ] Changes are covered by tests
    • [ ] New TODOs have a related JIRA ticket
    wip 
    opened by nbbeeken 0
  • feat(NODE-4867)!: WIP Testing BSON v5 DO NOT MERGE

    feat(NODE-4867)!: WIP Testing BSON v5 DO NOT MERGE

    Description WIP

    What is changing?

    Is there new documentation needed for these changes?

    What is the motivation for this change?

    Double check the following

    • [ ] Ran npm run check:lint script
    • [ ] Self-review completed using the steps outlined here
    • [ ] PR title follows the correct format: type(NODE-xxxx)[!]: description
      • Example: feat(NODE-1234)!: rewriting everything in coffeescript
    • [ ] Changes are covered by tests
    • [ ] New TODOs have a related JIRA ticket
    wip 
    opened by nbbeeken 0
  • feat(NODE-1603): add async_hooks support

    feat(NODE-1603): add async_hooks support

    Description

    What is changing?

    Adding minimal support for async_hooks to version 4.9.0. See #1846 for more details. This PR is a forward port of that.

    Is there new documentation needed for these changes?

    No

    What is the motivation for this change?

    We need to be able to use AsyncLocalStorage for an internal project. However without embedder API/async_hooks support the storage would be lost after a call to MongoDB. This PR enables async context tracking across MongoDB calls.

    Double check the following

    • [x] Ran npm run check:lint script
    • [x] Self-review completed using the steps outlined here
    • [x] PR title follows the correct format: <type>(NODE-xxxx)<!>: <description>
    • [x] Changes are covered by tests
    • [x] New TODOs have a related JIRA ticket (N/A)
    External Submission 
    opened by nathanlepori 3
Releases(v4.13.0)
  • v4.13.0(Dec 19, 2022)

    The MongoDB Node.js team is pleased to announce version 4.13.0 of the mongodb package!

    Features

    • NODE-4691: interrupt in-flight operations on heartbeat failure (#3457) (e641bd4)

    Bug Fixes

    • NODE-4447: disable causal consistency in implicit sessions (#3479) (6566fb5)
    • NODE-4834: ensure that MessageStream is destroyed when connections are destroyed (#3482) (8338bae)

    Documentation

    • Reference: https://docs.mongodb.com/drivers/node/current/
    • API: https://mongodb.github.io/node-mongodb-native/4.13/
    • Changelog: HISTORY.md

    We invite you to try the mongodb driver immediately, and report any issues to the NODE project.

    Source code(tar.gz)
    Source code(zip)
  • v4.12.1(Nov 23, 2022)

    The MongoDB Node.js team is pleased to announce version 4.12.1 of the mongodb package!

    Release Highlights

    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.

    Bug Fixes

    Documentation

    We invite you to try the mongodb library immediately, and report any issues to the NODE project.

    Source code(tar.gz)
    Source code(zip)
  • v4.12.0(Nov 16, 2022)

    The MongoDB Node.js team is pleased to announce version 4.12.0 of the mongodb package!

    Release Highlights

    ChangeStreams are now AsyncIterators

    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.

    Server Monitoring Fix When Monitoring Events are Skipped

    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.

    Performance Improvements with Buffering

    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.

    External Contributions

    Many thanks to @ImRodry for helping us fix the documentation for our deprecated callback overloads in this release!

    Features

    • NODE-4683: make ChangeStream an async iterable (#3454) (df8d9a4)

    Deprecations

    Bug Fixes

    • NODE-4609: allow mapping to falsey non-null values in cursors (#3452) (1bf6ef1)
    • NODE-4735: fix change stream consecutive resumabilty (#3453) (89b27e9)
    • NODE-4753: remove erroneous deprecation of geoNear (#3465) (199dcaf)
    • NODE-4783: handle orphaned operation descriptions (#3463) (4c9b4d8)

    Documentation

    We invite you to try the mongodb library immediately, and report any issues to the NODE project.

    Source code(tar.gz)
    Source code(zip)
  • v4.11.0(Oct 19, 2022)

    The MongoDB Node.js team is pleased to announce version 4.11.0 of the mongodb package!

    Release Highlights

    Recursive Schema Support

    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.

    AWS Authentication

    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.

    External Contributions

    Many thanks to those who contributed to this release!

    • @ermik provided an extremely large schema to test compilation with, which made testing our new recursive schema support possible with large schemas straightforward.
    • @noahsilas for documentation improvements in change streams and fixing our Typescript types for read preferences.
    • @zendagin for adding Typescript support for hashed indexes.
    • @biniona-mongodb for fixing our parsing of TLS options.
    • @LinusU for removing support for server versions lower than our minimum supported server version and improving error messages for unacknowledged writes with hints.

    Features

    • NODE-3651: add hashed index type (#3432) (f6b56a1)
    • NODE-3875: support recursive schema types (#3433) (26bce4a)
    • NODE-4503: throw original error when server attaches NoWritesPerformed label (#3441) (a7dab96)
    • NODE-4650: handle handshake errors with SDAM (#3426) (cbe7533)
    • NODE-4721: add aws-sdk as optional dependency (#3446) (b879cb5)

    Bug Fixes

    • NODE-3712,NODE-4546: electionId should be ordered before setVersion (#3174) (ca51fec)
    • NODE-3921: error on invalid TLS option combinations (#3405) (1a550df)
    • NODE-4186: accept ReadPreferenceLike in TransactionOptions type (#3425) (dc62bcb)
    • NODE-4475: make interrupted message more specific (#3437) (5f37cb6)
    • NODE-4608: prevent parallel monitor checks (#3404) (78bcfe4)
    • NODE-4647: improve error message (#3409) (0d3c02e)
    • NODE-4649: use SDAM handling for errors from min pool size population (#3424) (ef3b55d)

    Documentation

    • Reference: https://docs.mongodb.com/drivers/node/current/
    • API: https://mongodb.github.io/node-mongodb-native/4.11
    • Changelog: https://github.com/mongodb/node-mongodb-native/blob/main/HISTORY.md

    We invite you to try the mongodb library immediately, and report any issues to the NODE project.

    Source code(tar.gz)
    Source code(zip)
  • v4.10.0(Sep 19, 2022)

    The MongoDB Node.js team is pleased to announce version 4.10.0 of the mongodb package!

    Release Highlights

    Callback Deprecation

    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:

    • Using async/await syntax can yield the best experience with promise usage.
    • Using Node.js' callbackify utility is one approach:
      • require('util').callbackify(() => collection.findOne())(callback)
    • Using .then syntax is another:
      • collection.findOne().then(res => callback(null, res), err => callback(err))
    • And lastly, for large codebases still intertwined with callbacks we have an alternative package prepared.

    MongoDB-Legacy Callback Support

    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:

    • https://github.com/mongodb-js/nodejs-mongodb-legacy#readme

    Features

    • NODE-4385: add cmap pool pausing functionality (#3321) (335ee55)
    • NODE-4484: add experimental support for disambiguatedPaths in change stream documents (#3365) (846365a)
    • NODE-4519: deprecate promiseLibrary and PromiseProvider (#3403) (5c322b6)
    • NODE-4547: mark all callback APIs as deprecated (#3388) (a983f14)
    • NODE-4634: add support for bulk FindOperators.hint() (#3408) (8758890)

    Bug Fixes

    • NODE-3144: pool clear event ordering and retryability tests (#3407) (bdc0d67)
    • NODE-4557: randomize servers when there are only 2 eligible servers (#3390) (ddcfa49)
    • NODE-4583: revert nested union type support (#3383) (7f94f0a)
    • NODE-4591: only set loadBalanced on handshake when explicitly set (#3386) (57e9f2d)
    • NODE-4621: ipv6 address handling in HostAddress (#3410) (5eb3978)
    • NODE-4639: allow PromiseProvider to be null (#3412) (d29b3d9)

    Documentation

    • Reference: https://docs.mongodb.com/drivers/node/current/
    • API: https://mongodb.github.io/node-mongodb-native/4.10
    • Changelog: https://github.com/mongodb/node-mongodb-native/blob/main/HISTORY.md

    We invite you to try the mongodb library immediately, and report any issues to the NODE project.

    Source code(tar.gz)
    Source code(zip)
  • v4.9.1(Aug 31, 2022)

    The MongoDB Node.js team is pleased to announce version 4.9.1 of the mongodb package!

    Release Highlights

    This is a bug fix release as noted below.

    Bug Fixes

    • NODE-4583: revert nested union type support (#3383) (014d0b3)
    • NODE-4591: only set loadBalanced on handshake when explicitly set (#3386) (861d465)
    Source code(tar.gz)
    Source code(zip)
  • v4.9.0(Aug 18, 2022)

    The MongoDB Node.js team is pleased to announce version 4.9.0 of the mongodb package!

    Release Highlights

    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.

    Index Specification Detailed Fixes
    • Map as a valid input type in TS definition
    • Uses Map under the hood to ensure key order is preserved, fixed numeric index key order issue in combination with FLE usage
    • Tuples passed at the top level to createIndex were incorrectly parsed as string input
      • createIndex(['myKey', 1]) would create { 'myKey': 1, '1': 1 }.
      • Now it's correctly detected if the second arg is one of the known index directions.
      • For complex programmatic generation of indexes we recommend using a Map to avoid all the edge cases here.
    • Type strictness on this nesting of array (one or more)
    • Type strictness for createIndexes aligned with createIndex
      • No longer accepts just Document, checks that the values are a known IndexDirection

    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!

    • @sampaiodiego for the oplogReplay flag support fix
    • @jer-sen for typescript Filter definition improvements
    • @aditi-khare-mongoDB for index specification fixes / type improvements

    Features

    • NODE-3517: improve index spec handling and type definitions (#3315) (0754bf9)
    • NODE-4336: deprecate old write concern options and add missing writeConcern to MongoClientOptions (#3340) (d2b6ad8)

    Bug Fixes

    • NODE-4159,NODE-4512: remove servers with incorrect setName from topology and fix unix socket parsing (#3348) (00dcf2d)
    • NODE-4273: pass 'comment' option through to distinct command (#3339) (753ecfe)
    • NODE-4413: set maxTimeMS on getMores when maxAwaitTimeMS is specified (#3319) (dcbfd6e)
    • NODE-4429: select server sync for endSessions during close (#3363) (5086ead)
    • NODE-4467: Add back support for oplogReplay option as deprecated (#3337) (6c69b7d)
    • NODE-4496: counter values incorrectly compared when instance of Long (#3342) (d29eb8c)
    • NODE-4513: type for nested objects in query & update (#3349) (ec1a68f)

    Documentation

    • Reference: https://docs.mongodb.com/drivers/node/current/
    • API: https://mongodb.github.io/node-mongodb-native/4.8
    • Changelog: https://github.com/mongodb/node-mongodb-native/blob/main/HISTORY.md

    We invite you to try the mongodb library immediately, and report any issues to the NODE project.

    Source code(tar.gz)
    Source code(zip)
  • v4.8.1(Jul 26, 2022)

    The MongoDB Node.js team is pleased to announce version 4.8.1 of the mongodb package!

    Release Highlights

    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!

    Bug Fixes

    • NODE-4423: better type support for nested objects in query & update (#3328) (05e007b)
    • NODE-4425: webpack optional import of FLE issue (#3324) (5ab2b05)
    • NODE-4444: use Node.js clear timers (#3327) (c5cfe21)

    Documentation

    • Reference: https://docs.mongodb.com/drivers/node/current/
    • API: https://mongodb.github.io/node-mongodb-native/4.8
    • Changelog: https://github.com/mongodb/node-mongodb-native/blob/main/HISTORY.md

    We invite you to try the mongodb library immediately, and report any issues to the NODE project.

    Source code(tar.gz)
    Source code(zip)
  • v4.8.0(Jul 13, 2022)

    The MongoDB Node.js team is pleased to announce version 4.8.0 of the mongodb package!

    Release Highlights

    UpdateFilter nested fields

    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: image1

    Optional client.connect() fixup

    In 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 preferred collection.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.

    Features

    • NODE-4078: allow comment with estimated doc count (#3301) (bed1fe3)
    • NODE-4267: support nested fields in type completion for UpdateFilter (#3259) (1a9a44c)

    Bug Fixes

    • NODE-4125: change stream resumability (#3289) (aa5f97e)
    • NODE-4262: make startSession work without a connection (#3286) (89ad7c3)

    Documentation

    • Reference: https://docs.mongodb.com/drivers/node/current/
    • API: https://mongodb.github.io/node-mongodb-native/4.8
    • Changelog: https://github.com/mongodb/node-mongodb-native/blob/main/HISTORY.md

    We invite you to try the mongodb library immediately, and report any issues to the NODE project.

    Source code(tar.gz)
    Source code(zip)
  • v4.7.0(Jun 7, 2022)

    The MongoDB Node.js team is pleased to announce version 4.7.0 of the mongodb package! Happy MongoDB World Day!

    Release Highlights

    Support for ZSTD Compression

    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.

    Improved Connection Storm Avoidance

    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 });
    

    Expanded Change Stream Events

    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 Stream Support of Pre/Post Images

    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.

    Improved Performance in Serverless Environments

    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.

    Estimated Document Count uses the Count command

    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.

    MongoClient.connect is now optional

    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.

    Support for Clustered Collections

    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/

    Automatic Encryption Shared Library

    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 Preview

    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:

    • NODE-1837: add zstd compression option (#3237) (1261432)
    • NODE-2993: implement maxConnecting (#3255) (c9d3816)
    • NODE-3750: make maxConnecting configurable (#3261) (ee41447)
    • NODE-3938: Add support for pre/post images in change streams (#3250) (981465c)
    • NODE-4079: estimated document count uses count (#3244) (a752e75)
    • NODE-4081: fix and deprecate change stream resume options (#3270) (47adfb3)
    • NODE-4139: streaming protocol message changes (#3256) (4b9ad77)
    • NODE-4192: make MongoClient.connect optional (#3232) (a2359e4)
    • NODE-4196: add support for showExpandedEvents in change streams (#3254) (9c1782e)
    • NODE-4229: bump maxWireVersion to 17 (#3265) (d13cec2)

    Bug Fixes

    • NODE-4103: respect BSON options when creating change streams (#3247) (b2798d9)
    • NODE-4108: improve return type for withTransaction() (#3236) (48e0e6e)
    • NODE-4254: allow csfle to be dynamically required (#3260) (cd6b5a0)
    • NODE-4281: ensure that the driver always uses Node.js timers (#3275) (4501a1c)

    Documentation

    • Reference: https://docs.mongodb.com/drivers/node/current/
    • API: https://mongodb.github.io/node-mongodb-native/4.7
    • Changelog: https://github.com/mongodb/node-mongodb-native/blob/main/HISTORY.md

    We invite you to try the mongodb library immediately, and report any issues to the NODE project.

    Source code(tar.gz)
    Source code(zip)
  • v4.6.0(May 11, 2022)

    The MongoDB Node.js team is pleased to announce version 4.6.0 of the mongodb package!

    Release Highlights

    TypeScript: ChangeStreamDocument

    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.

    Performance: Consider Server Load During Server Selection

    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.

    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 official driver API and is subject to change without notice.

    Features

    • NODE-2992: consider server load during server selection (#3219) (35eeba3)
    • NODE-4059: ChangeStreamDocument not fully typed to specification (#3191) (8b24212)

    Bug Fixes

    • NODE-3565: Improve error message for insertMany with partially empty array (#3221) (0ef2516)
    • NODE-4232: stream() also returns generic AsyncIterable (ed4ba58)
    • NODE-3688: make handshake errors retryable (#3165) (3f8765a)
    • NODE-3833: return early on end if gridfs upload stream is already ended (#3223) (c27e844)
    • NODE-3928: don't throw error in Response constructor (#3199) (441fc63)
    • NODE-4031: options parsing for array options (#3193) (4b2e3d1)
    • NODE-4133: array field NestedPaths return type (#3184) (c46c984)
    • NODE-4156: remove comment from commands pre-4.4 (#3195) (4e6dccd)
    • NODE-4188: default localThresholdMS to 15ms (#3207) (5e730ff)
    • NODE-4208: add aws http request timeout handler (#3225) (829d7be)

    Documentation

    • Reference: https://docs.mongodb.com/drivers/node/current/
    • API: https://mongodb.github.io/node-mongodb-native/4.6
    • Changelog: https://github.com/mongodb/node-mongodb-native/blob/main/HISTORY.md

    We invite you to try the mongodb library immediately, and report any issues to the NODE project.

    Source code(tar.gz)
    Source code(zip)
  • v4.6.0-alpha.0(May 4, 2022)

    The MongoDB Node.js team is pleased to announce version v4.6.0-alpha.0 of the mongodb package!

    Release Highlights

    This release is for internal testing - NOT intended for use production.

    Features

    Bug Fixes

    Documentation

    • Reference: https://docs.mongodb.com/drivers/node/current/
    • API: https://mongodb.github.io/node-mongodb-native/4.5
    • Changelog: https://github.com/mongodb/node-mongodb-native/blob/main/HISTORY.md
    Source code(tar.gz)
    Source code(zip)
  • v4.5.0(Apr 4, 2022)

    The MongoDB Node.js team is pleased to announce version 4.5.0 of the mongodb package!

    Release Highlights

    This release includes a number of enhancements noted below.

    comment option support

    The 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" } } }
      }
    }
    

    Socket timeout fixes for FaaS environments

    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.

    TS fixes for 4.7

    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.

    Features

    • NODE-3697: reduce serverSession allocation (#3171) (5132bc9)
    • NODE-3699: add support for comment field (#3167) (4e2f9bf)
    • NODE-4014: Add let option to bulk write operations (#3160) (6f633d1)

    Bug Fixes

    • NODE-3769: retryable writes are not compliant with specification (#3144) (ff26b12)
    • NODE-3810: delay timeout errors by one event loop tick (#3180) (0ed7cbf)
    • NODE-4069: remove 'default' from options for fullDocument field in change stream options (#3169) (799689e)
    • NODE-4074: ensure getTopology doesn't throw synchronously (#3172) (329f081)
    • NODE-4129: constrain watch type parameter to extend ChangeStream type parameter (#3183) (43ba9fc)

    Documentation

    • Reference: https://docs.mongodb.com/drivers/node/current/
    • API: https://mongodb.github.io/node-mongodb-native/4.5
    • Changelog: https://github.com/mongodb/node-mongodb-native/blob/main/HISTORY.md

    We invite you to try the mongodb library immediately, and report any issues to the NODE project.

    Source code(tar.gz)
    Source code(zip)
  • v4.4.1(Mar 3, 2022)

    The MongoDB Node.js team is pleased to announce version 4.4.1 of the mongodb package!

    Bug Fixes

    • NODE-3521: update session support checks (#3151) (aaa453d)
    • NODE-3948: Add error code to MongoSystemError (#3149) (446da95)

    Documentation

    • Reference: https://docs.mongodb.com/drivers/node
    • API: https://mongodb.github.io/node-mongodb-native/4.4
    • Changelog: https://github.com/mongodb/node-mongodb-native/blob/main/HISTORY.md

    We invite you to try the mongodb library immediately, and report any issues to the NODE project.

    Source code(tar.gz)
    Source code(zip)
  • v4.4.0(Feb 17, 2022)

    The MongoDB Node.js team is pleased to announce version 4.4.0 of the mongodb package!

    Release Highlights

    This release includes a few new features described below.

    KMIP

    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' }}}})
    

    CSFLE TLS

    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.

    Kerberos

    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')
    

    ⚠️ collection.count() and cursor.count()

    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:

    • If a query is passed in, collection.count will behave the same as collection.countDocuments and perform a collection scan.
    • If no query is passed in, 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.

    Features

    • NODE-2938: add service host mechanism property (#3130) (46d5821)
    • NODE-2939: add new hostname canonicalization opts (#3131) (d0390d0)
    • NODE-3351: use hostname canonicalization (#3122) (f5c76f3)
    • NODE-3777: add csfle kmip support (#3070) (44bbd6e)
    • NODE-3867: deprecate cursor count and update v4 docs (#3127) (a48d7e2)

    Bug Fixes

    • NODE-3621: fixed type of documentKey property on ChangeStreamDocument (#3118) (c63a21b)
    • NODE-3795: unexpected No auth provider for DEFAULT defined error (#3092) (fb38a56)
    • NODE-3813: unexpected type conversion of read preference tags (#3138) (3e7b894)
    • NODE-3878: use legacy count operation on collection.count (#3126) (12c6835)
    • NODE-3917: Throw an error when directConnection is set with multiple hosts (#3143) (b192493)

    Documentation

    • Reference: https://docs.mongodb.com/drivers/node
    • API: https://mongodb.github.io/node-mongodb-native/4.4
    • Changelog: https://github.com/mongodb/node-mongodb-native/blob/main/HISTORY.md

    We invite you to try the mongodb library immediately, and report any issues to the NODE project.

    Source code(tar.gz)
    Source code(zip)
  • v4.3.1(Jan 18, 2022)

    The MongoDB Node.js team is pleased to announce version 4.3.1 of the mongodb package!

    Release Highlights

    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:

    • type checking defaults to any after the first level of recursion for self-referential types
    interface 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'
      }
    });
    
    • indirectly self-referential types are still not supported
    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({});
    

    Bug Fixes

    • NODE-3792: remove offensive language throughout the codebase (#3091) (8e2b0cc)
    • NODE-3852,NODE-3854,NODE-3856: Misc typescript fixes for 4.3.1 (#3102) (dd5195a)

    Documentation

    • Reference: https://docs.mongodb.com/drivers/node
    • API: https://mongodb.github.io/node-mongodb-native/4.3
    • Changelog: https://github.com/mongodb/node-mongodb-native/blob/main/HISTORY.md

    We invite you to try the mongodb library immediately, and report any issues to the NODE project.

    Source code(tar.gz)
    Source code(zip)
  • v4.3.0(Jan 6, 2022)

    The MongoDB Node.js team is pleased to announce version 4.3.0 of the mongodb package!

    Release Highlights

    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.

    Performance

    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 });
    

    TypeScript

    Type inference for nested documents

    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: Screen Shot 2022-01-06 at 5 29 17 PM

    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.

    Consistent type inference for the _id type

    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:

    • If no _id is specified on the schema, it is inferred to be of type ObjectId and is optional on inserts.
    • If an _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.
    • If an _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.

    Features

    • NODE-3589: support dot-notation attributes in Filter (#2972) (76fff97)
    • NODE-3633: add Socks5 support (#3041) (451627a)
    • NODE-3784: Add enableUtf8Validation option (#3074) (4f56409)

    Bug Fixes

    • gridfs: make GridFSBucketWriteStream.prototype.end() return this for compat with @types/[email protected] (#3088) (7bb9e37)
    • NODE-2899: sort and correct circular imports (#3072) (48cc729)
    • NODE-3675: SRV option bug correctly defaults authSource to $external (#3079) (30f2a2d)
    • NODE-3803: Fix _id typing on collection create operations (#3077) (f1979db)

    Documentation

    • Reference: https://docs.mongodb.com/drivers/node
    • API: https://mongodb.github.io/node-mongodb-native/4.3
    • Changelog: https://github.com/mongodb/node-mongodb-native/blob/main/HISTORY.md

    We invite you to try the mongodb library immediately, and report any issues to the NODE project.

    Source code(tar.gz)
    Source code(zip)
  • v4.2.2(Dec 13, 2021)

    The MongoDB Node.js team is pleased to announce version 4.2.2 of the mongodb package!

    Bug Fixes

    • NODE-3705: ReadPreference.fromOptions omitting hedge and maxStalenessSeconds when readPreference is a string (#3060) (b9fbac5)
    • NODE-3711: retry txn end on retryable write (#3045) (7b00d0f)
    • NODE-3765: make replacement for replaceOne operations without _id (#3040) (e07e564)
    • stricter protocol check in connection string (#3078) (bc05671)

    Documentation

    • Reference: https://docs.mongodb.com/drivers/node
    • API: https://mongodb.github.io/node-mongodb-native/4.2
    • Changelog: https://github.com/mongodb/node-mongodb-native/blob/main/HISTORY.md

    We invite you to try the mongodb library immediately, and report any issues to the NODE project.

    Source code(tar.gz)
    Source code(zip)
  • v4.2.1(Nov 30, 2021)

    The MongoDB Node.js team is pleased to announce version 4.2.1 of the mongodb package!

    Release Highlights

    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.

    Bug Fixes

    • NODE-2370: correct a return type of hasNext() (#3058) (b6a63df)
    • NODE-3627: Enable flexible BSON validation for server error key containing invalid utf-8 (#3054) (7a507f0)
    • NODE-3648: run get more ops through server selection (#3030) (268e211)
    • NODE-3767: don't delete dbName if authSource is provided (#3055) (0a830e2)
    • NODE-3770: Filter type uses WithId on the schema (#3053) (307d623)

    Documentation

    • Reference: https://docs.mongodb.com/drivers/node
    • API: https://mongodb.github.io/node-mongodb-native/4.2
    • Changelog: https://github.com/mongodb/node-mongodb-native/blob/main/HISTORY.md

    We invite you to try the mongodb library immediately, and report any issues to the NODE project.

    Source code(tar.gz)
    Source code(zip)
  • v4.2.0(Nov 17, 2021)

    Release Highlights

    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.

    Features

    • NODE-3083: support aggregate writes on secondaries (#3022) (f696909)
    • NODE-3446: deprecate mapReduce command (#3036) (b6c73bf)
    • NODE-3467: implement srvMaxHosts, srvServiceName options (#3031) (1f8b539)
    • NODE-3469,NODE-3615,NODE-3507: update min and max wire versions (#3014) (2a78d5a)
    • NODE-3691: make time series options granularity type strict (#3005) (98017f9)
    • NODE-3692: make change stream events typing more generic (#3034) (d5ae78e)
    • NODE-3728: Allow to pass authorizedCollections option to the db.listCollections method (#3021) (e1234a7)
    • NODE-3729: add withId to default return type for collection.find and collection.findOne (#3039) (52520aa)

    Bug Fixes

    • NODE-3116: reschedule unreliable async interval first (#3006) (33886a7)
    • NODE-3344: allow setting defaultTransactionOptions with POJO rather than ReadConcern instance (#3032) (53b3164)
    • NODE-3515: do proper opTime merging in bulk results (#3012) (43300c3)
    • NODE-3668: compile error with OptionalId on TS 4.5 beta (#3004) (ee7f095)
    • NODE-3726: add optional option overloads of Db's createCollection function (#3019) (c3149e1)
    • NODE-3727: add overloads for BulkOperationBase's execute function (#3018) (216d194)

    Documentation

    • Reference: https://docs.mongodb.com/drivers/node
    • API: https://mongodb.github.io/node-mongodb-native/4.2
    • Changelog: https://github.com/mongodb/node-mongodb-native/blob/main/HISTORY.md

    We invite you to try the mongodb library immediately, and report any issues to the NODE project.

    Source code(tar.gz)
    Source code(zip)
  • v4.1.4(Nov 3, 2021)

    Release Highlights

    This release includes a couple of bug fixes as noted below:

    Bug Fixes

    • NODE-3515: do proper opTime merging in bulk results (#3012) (43300c3)
    • NODE-3668: compile error with OptionalId on TS 4.5 beta (#3004) (ee7f095)

    Documentation

    • Reference: https://docs.mongodb.com/drivers/node
    • API: https://mongodb.github.io/node-mongodb-native/4.1
    • Changelog: https://github.com/mongodb/node-mongodb-native/blob/4.1/HISTORY.md

    We invite you to try the mongodb library immediately, and report any issues to the NODE project.

    Source code(tar.gz)
    Source code(zip)
  • v3.7.3(Oct 20, 2021)

    The MongoDB Node.js team is pleased to announce version 3.7.3 of the mongodb package!

    What's Changed

    • fix(NODE-3515): do proper opTime merging in bulk results by @durran in https://github.com/mongodb/node-mongodb-native/pull/3011

    Full Changelog: https://github.com/mongodb/node-mongodb-native/compare/v3.7.2...v3.7.3

    Documentation

    • Reference: https://docs.mongodb.com/drivers/node
    • API: https://mongodb.github.io/node-mongodb-native/3.7
    • Changelog: https://github.com/mongodb/node-mongodb-native/blob/3.7/HISTORY.md

    We invite you to try the mongodb library immediately, and report any issues to the NODE project.

    Source code(tar.gz)
    Source code(zip)
  • v4.1.3(Oct 5, 2021)

    The MongoDB Node.js team is pleased to announce version 4.1.3 of the mongodb package!

    Release Highlights

    This release includes a couple of TypeScript fixes as noted below:

    Bug Fixes

    • NODE-3609: correct listDatabases return type (#2986) (a8e9938)
    • NODE-3624: Incorrect default aggregation generic type (#2987) (440517e)

    Documentation

    • Reference: https://docs.mongodb.com/drivers/node
    • API: https://mongodb.github.io/node-mongodb-native/4.1
    • Changelog: https://github.com/mongodb/node-mongodb-native/blob/4.1/HISTORY.md

    We invite you to try the mongodb library immediately, and report any issues to the NODE project.

    Source code(tar.gz)
    Source code(zip)
  • v3.7.2(Oct 5, 2021)

    The MongoDB Node.js team is pleased to announce version 3.7.2 of the mongodb package!

    Release Highlights

    This release contains a fix for optional require of dependencies on yarn berry.

    Bug Fixes

    • NODE-3622: bump optional-require for additional yarn berry pnp support (#2989) (ec23d6302)

    Documentation

    • Reference: https://docs.mongodb.com/drivers/node
    • API: https://mongodb.github.io/node-mongodb-native/3.7
    • Changelog: https://github.com/mongodb/node-mongodb-native/blob/3.7/HISTORY.md

    We invite you to try the mongodb library immediately, and report any issues to the NODE project.

    Source code(tar.gz)
    Source code(zip)
  • v4.1.2(Sep 14, 2021)

    The MongoDB Node.js team is pleased to announce version 4.1.2 of the mongodb package!

    Release Highlights

    This release addresses a number of bug fixes, please peruse the list below for more information on each fix.

    Bug Fixes

    • NODE-3434: errInfo should be exposed on bulk write (#2977) (6b3c161)
    • NODE-3467: allow object type for aggregate out helper (#2971) (cd603e8)
    • NODE-3487: check for nullish aws mechanism property (#2951) (78ec0dd)
    • NODE-3559: incorrect GridFS stream type (#2981) (3915ea8)
    • NODE-3567: correct typing on aggregation out helper (#2967) (a299a0b)
    • NODE-3574: reintroduce ObjectID export (#2965) (2291119)
    • NODE-3585: MongoClientOptions#compressors has incorrect type (#2976) (f1b896d)
    • NODE-3591: tlsCertificateKeyFile option does not default cert (#2979) (6d42267)
    • NODE-3599: incorrect indexes return type (#2980) (122b9f3)

    Documentation

    • Reference: https://docs.mongodb.com/drivers/node
    • API: https://mongodb.github.io/node-mongodb-native/4.1
    • Changelog: https://github.com/mongodb/node-mongodb-native/blob/4.1/HISTORY.md

    We invite you to try the mongodb library immediately, and report any issues to the NODE project.

    Source code(tar.gz)
    Source code(zip)
  • v3.7.1(Sep 14, 2021)

    The MongoDB Node.js team is pleased to announce version 3.7.1 of the mongodb package!

    Release Highlights

    This release contains an internal improvement that makes our monitor utilize the new hello handshake for monitoring when available.

    Features

    • NODE-3424: use hello for monitoring commands (#2964) (910c564)

    Documentation

    • Reference: https://docs.mongodb.com/drivers/node
    • API: https://mongodb.github.io/node-mongodb-native/3.7
    • Changelog: https://github.com/mongodb/node-mongodb-native/blob/3.7/HISTORY.md

    We invite you to try the mongodb library immediately, and report any issues to the NODE project.

    Source code(tar.gz)
    Source code(zip)
  • v3.7.0(Aug 31, 2021)

    The MongoDB Node.js team is pleased to announce version 3.7.0 of the mongodb package!

    Release Highlights

    Versioned API

    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 an API version on a client

    // Declare API version "1" for the client
    client = new MongoClient(uri, { serverApi: { version: '1' } });
    
    cursor = client.db('database').collection('coll').find(...);
    

    Strict mode

    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 });
    

    Deprecation Errors

    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.
    

    Features

    Bug Fixes

    • NODE-3377: driver should allow arbitrary explain levels (#2961) (96c8ab4)
    • NODE-3463: pass explain error through to callback (#2949) (e5975af)

    Documentation

    • Reference: https://docs.mongodb.com/drivers/node/current/
    • API: https://mongodb.github.io/node-mongodb-native/3.7/api/
    • Changelog: https://github.com/mongodb/node-mongodb-native/blob/v3.7.0/HISTORY.md

    We invite you to try the mongodb library immediately, and report any issues to the NODE project.

    Source code(tar.gz)
    Source code(zip)
  • v3.6.12(Aug 30, 2021)

    The MongoDB Node.js team is pleased to announce version 3.6.12 of the mongodb package!

    Bug Fixes

    • NODE-3487: check for nullish aws mechanism property (#2957) (5902b4c)
    • NODE-3528: add support for snappy v7 (#2947) (54f5c2d)

    Documentation

    • Reference: https://docs.mongodb.com/drivers/node/current/
    • API: https://mongodb.github.io/node-mongodb-native/3.6/api/
    • Changelog: https://github.com/mongodb/node-mongodb-native/blob/v3.6.12/HISTORY.md

    We invite you to try the mongodb library immediately, and report any issues to the NODE project.

    Source code(tar.gz)
    Source code(zip)
  • v4.1.1(Aug 24, 2021)

    The MongoDB Node.js team is pleased to announce version 4.1.1 of the mongodb package!

    Release Highlights

    Error handling

    We introduced better organization and consistency to our existing errors in an effort to provide more detailed error types that can help identify issues clearly and quickly. Our readme has a new section that describes how to handle errors thrown by the driver and defines our approach to semver in the context of errors. Notably, we recommend only using instanceof checks to filter for a given error class as we do not guarantee error messages or names will be preserved between patch releases, only the subclass hierarchy.

    Thanks so much to our summer interns @andymina and @W-A-James for undertaking this effort!

    Notable fixes

    • This version of the driver brings in the latest BSON release which includes deserialization performance improvements.
    • The snappy package recently released a major version bump (v7) that makes use of a rust implementation of Snappy compression. Our driver can now make use of this version (while maintaining compatibility with the previous v6).
    • findOne() once again correctly returns null when no match is found instead of undefined. This change was unintentional and not consistent with our other APIs. It slipped through testing due to the nature of undefined and null being nearly (==) but not actually (===) equal. We apologize if this results in the need for any code changes.

    This release also addresses some Typescript issues that require further explanation, let's dive in:

    TypeScript support

    Projections

    Starting in MongoDB 4.4 projections can accept aggregation expressions and aggregation syntax. This empowers users to create some pretty amazing and complex data model transformations on the database side. Unfortunately, our initial release of typescript typing for projections was too narrow to allow these use cases and still pass the compiler checks. Now projections are generic objects and the result of a cursor with a projection is typed as a generic object by default.

    The recommended usage for projections alongside typescript is as follows:

    interface Pet {
        name: string;
        buddies: Pet[];
    }
    interface PetBuddyCount {
        name: string;
        buddyCount: number;
    }
    
    const pets = db.collection<Pet>('pets');
    
    const petBuddyCounts = await pets.find().project<PetBuddyCount>({
        name: 1,
        buddyCount: { $size: '$buddies' },
    }).toArray();
    

    By using a parameterized .project call you can now get the correct type information on the petBuddyCounts array. You will need to build the projection type yourself based on the projection you define for your query, but this has the benefit of constraining your results to precisely your type expectations.

    Generics in find/findOne

    In our initial typescript release the find and findOne methods accepted a generic parameter that was passed to the filter argument of the API.

    find<T>(f: Filter<T>): FindCursor<T>
    

    Due to how typescript automatically resolves the types of generics, one could run into an issue when specifying a filter that was incorrectly typed. The code below should be a Typescript error, TS hints to us the name is a string so it should only allow an array of string for $in.

    // (using the same pets collection from the last example)
    pets.find({ name: { $in: [1, 2] } });
    // instead of the expected FindCursor<Pet> type TS was resolving to:
    const res: FindCursor<{name: {$in: number[]}}> = pets.find(/* same arg as above */);
    

    It uses the incorrectly typed filter that does not match the schema of Filter<TSchema> to automatically resolve a crazy return type. The function definition has now been updated to be:

    find<T>(f: Filter<TSchema>): FindCursor<T>
    

    So the Filter argument will no longer be automatically resolved to the passed in type, giving us the typescript compiler errors we love so much!

    Bug Fixes

    • NODE-3454: projection types are too narrow (#2924) (48d6da9)
    • NODE-3468: remove generic overrides from find (#2935) (74bd7bd)
    • NODE-3511: deprecate fullResponse and remove associated buggy code paths (#2943) (dfc39d1)
    • NODE-3528: add support for snappy 7 (#2939) (0f7f300)
    • NODE-3546: revert findOne not found result type to null (#2945) (1c576e9)

    Refactoring

    Documentation

    • Reference: https://docs.mongodb.com/drivers/node
    • API: https://mongodb.github.io/node-mongodb-native/4.0
    • Changelog: https://github.com/mongodb/node-mongodb-native/blob/4.1/HISTORY.md

    We invite you to try the mongodb library immediately, and report any issues to the NODE project.

    Source code(tar.gz)
    Source code(zip)
  • v3.6.11(Aug 5, 2021)

    The MongoDB Node.js team is pleased to announce version 3.6.11 of the mongodb package!

    Release Highlights

    This patch addresses a few bugs listed below. Notably, we fixed an issue with the way we imported one of our optional dependencies that blocked webpack bundling.

    If you are a webpack user you will still get warnings for our optional dependencies (if you don't use them). You can hush the warnings by adding this option to your webpack config:

    {
        // ...
        externals: [
            'mongodb-client-encryption',
            'aws4',
            'saslprep',
            'kerberos',
            'snappy',
            'bson-ext',
        ],
        // ...
    }
    

    It is important to note that this will leave the imports in place and not pull in the code to your bundle. If you later do adopt using these dependencies you'll want to revert the relevant setting.

    Bug Fixes

    • NODE-1843: bulk operations ignoring provided sessions (#2898) (9244b17)
    • NODE-3199: unable to bundle driver due to uncaught require (#2903) (60efe9d)

    Documentation

    • Reference: https://docs.mongodb.com/drivers/node/current/
    • API: http://mongodb.github.io/node-mongodb-native/3.6/api
    • Changelog: https://github.com/mongodb/node-mongodb-native/blob/3.6/HISTORY.md

    We invite you to try the mongodb package immediately, and report any issues to the NODE project.

    Source code(tar.gz)
    Source code(zip)
Couchbase Node.js Client Library (Official)

Couchbase Node.js Client The Node.js SDK library allows you to connect to a Couchbase cluster from Node.js. It is a native Node.js module and uses the

null 460 Nov 13, 2022
Nano: The official Apache CouchDB library for Node.js

Nano Offical Apache CouchDB library for Node.js. Features: Minimalistic - There is only a minimum of abstraction between you and CouchDB. Pipes - Prox

The Apache Software Foundation 578 Dec 24, 2022
TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, MariaDB, PostgreSQL and SQLite databases.

TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, MariaDB, PostgreSQL and SQLite datab

MikroORM 5.4k Dec 31, 2022
🍹 MongoDB ODM for Node.js apps based on Redux

Lightweight and flexible MongoDB ODM for Node.js apps based on Redux. Features Flexible Mongorito is based on Redux, which opens the doors for customi

Vadim Demedes 1.4k Nov 30, 2022
A high performance MongoDB ORM for Node.js

Iridium A High Performance, IDE Friendly ODM for MongoDB Iridium is designed to offer a high performance, easy to use and above all, editor friendly O

Sierra Softworks 570 Dec 14, 2022
A back-end server aplication created using node.js, express and mongodb.

Course Material and FAQ for my Complete Node.js, Express and MongoDB Bootcamp This repo contains starter files and the finished project files for all

Pablo César Jiménez villeda 1 Jan 4, 2022
5-BackControlFinanzas - Node & MongoDB

API para APP 'Control Finanzas' Pequeña API/Backend creada para la aplicacion personal de Control Finanzas. Enlace de github a la aplicacion que requi

Ignacio Tirado 1 Jan 3, 2022
A Node.js ORM for MySQL, SQLite, PostgreSQL, MongoDB, GitHub and serverless service like Deta, InspireCloud, CloudBase, LeanCloud.

Dittorm A Node.js ORM for MySQL, SQLite, PostgreSQL, MongoDB, GitHub and serverless service like Deta, InspireCloud, CloudBase, LeanCloud. Installatio

Waline 21 Dec 25, 2022
A node.js locks library with support of Redis and MongoDB

locco A small and simple library to deal with race conditions in distributed systems by applying locks on resources. Currently, supports locking via R

Bohdan 5 Dec 13, 2022
Official turtleDB project

Overview • Getting Started • Features • Contributors • License • Overview turtleDB is a JavaScript framework and in-browser database for developers to

turtleDB 436 Dec 24, 2022
Run official FLAC tools `flac` and `metaflac` as WebAssembly, on browsers or Deno.

flac.wasm Run official FLAC tools flac and metaflac as WebAssembly, on browsers or Deno. Currently we have no plans on supporting Node.js. Try it onli

Pig Fang 15 Aug 21, 2022
MongoDB object modeling designed to work in an asynchronous environment.

Mongoose Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. Mongoose supports both promises and callbacks. Do

Automattic 25.2k Dec 30, 2022
The ultimate solution for populating your MongoDB database.

Mongo Seeding The ultimate solution for populating your MongoDB database ?? Define MongoDB documents in JSON, JavaScript or even TypeScript files. Use

Paweł Kosiec 494 Dec 29, 2022
📇 Generates and parses MongoDB BSON UUIDs

uuid-mongodb Generates and parses BSON UUIDs for use with MongoDB. BSON UUIDs provide better performance than their string counterparts. Inspired by @

Carmine DiMascio 96 Nov 21, 2022
A MongoDB-like database built on top of Hyperbee with support for indexing

hyperbeedeebee A MongoDB-like database built on top of Hyperbee with support for indexing WIP: There may be breaking changes in the indexing before th

null 35 Dec 12, 2022
E-Commerce Application developed with nodejs and stored to mongodb.

E-Commerce Application This Application has been developed with nodejs and mongodb. Environment Variables Create a file named config.env in config dir

Abdullah Öztürk 13 Dec 23, 2021
Database manager for MySQL, PostgreSQL, SQL Server, MongoDB, SQLite and others. Runs under Windows, Linux, Mac or as web application

Database manager for MySQL, PostgreSQL, SQL Server, MongoDB, SQLite and others. Runs under Windows, Linux, Mac or as web application

DbGate 2k Dec 30, 2022
The Wholesome App. A project that allows you to upload images directly to MongoDB Atlas into your collection, a faster cloud database.

The Wholesome App. A project that allows you to upload images directly to MongoDB Atlas into your collection, a faster cloud database. To upload your cute and wholesome images.

Gourav Singh Rawat 2 Jul 17, 2022
A joi extension to validate MongoDB's ObjectIDs

@marsup/joi-objectid This is a simple joi extension to validate MongoDB's ObjectIDs. Installation npm install --save @marsup/joi-objectid Usage const

Nicolas Morel 2 Dec 15, 2022