MongoDB Node.js Driver

repository·main·Indexed 27 days ago

https://github.com/mongodb/node-mongodb-native

The official MongoDB driver for Node.js (version 7.5.0), providing high-performance access to MongoDB databases. It supports MongoDB servers version 4.2+ and features Client-Side Field Level Encryption and various compression algorithms. The driver can be extended with official packages such as @mongodb-js/zstd, mongodb-client-encryption, and kerberos.

Tokens
20.1K
Snippets
53
Records
132
Agent score
93%

What's inside mongodb

  1. Understand the MongoDB Node.js Driver error hierarchy

    main

    All errors in the Node.js driver derive from the MongoError class. While MongoError is the base, it should never be directly instantiated.

    There are five primary error branches:

    1. MongoDriverError: Errors originating in the driver or caused by incorrect driver usage. This is the most common branch for developers.
    2. MongoNetworkError: Errors preventing connection to a MongoDB server.
    3. MongoServerError: Errors wrapping responses received directly from the MongoDB server.
    4. MongoSystemError: Errors originating from faulty environment setup (e.g., MongoServerSelectionError).
    5. MongoCryptError: Errors thrown from client-side encryption logic.
  2. Enable Retryable Writes via Connection String

    main
    Starting with MongoDB 3.6 support, the Node.js driver allows for retryable writes through the connection string. This enables at-most-once semantics for write operations, allowing the driver to retry operations if it fails to obtain a write result due to network errors or replica set failovers.
  3. Migrate from Collection.mapReduce() to Aggregation or Db.command()

    main

    The Collection.mapReduce() helper was removed in v5. Since MongoDB server 5.0, it is recommended to migrate to the aggregation pipeline. If you must use the raw mapReduce command, use the Db.command() helper. When using Db.command(), all mapReduce options must be specified directly on the command object rather than passed through an options object.

    // Manually running the command using `db.command()`
    const command = {
      mapReduce: 'my-collection',
      map: 'function() { emit(this.user_id, 1); }',
      reduce: 'function(k,vals) { return 1; }',
      out: 'inline',
      readConcern: 'majority'
    };
    
    await db.command(command);
  4. Connect to MongoDB using MongoClient

    main

    Use MongoClient to establish a connection to your MongoDB server.

    Note on DNS Resolution: In Node.js 18+, localhost might resolve to an IPv6 address, causing connection failures. To resolve this, you can:

    • Use the family option: new MongoClient(url, { family: 4 })
    • Use 127.0.0.1 instead of localhost in the connection string.
    • Use the --dns-resolution-order=ipv4first Node.js flag.
    const { MongoClient } = require('mongodb');
    
    const url = 'mongodb://localhost:27017';
    const client = new MongoClient(url);
    const dbName = 'myProject';
    
    async function main() {
      await client.connect();
      const db = client.db(dbName);
      const collection = db.collection('documents');
      // Perform operations here
      return 'done.';
    }
    
    main()
      .then(console.log)
      .catch(console.error)
      .finally(() => client.close());
  5. Generate API documentation for a new major or minor version

    main

    To generate API documentation for a new major or minor release, use the build:docs script. The version must be provided using the --tag option in MAJOR.MINOR format (e.g., 6.8).

    Options:

    • --tag <version>: The version to document (format: MAJOR.MINOR).
    • --yes: Silences prompts (recommended for CI environments).
    • --status <status>: Sets the status of the version.

    After generation, you can preview the documentation locally using npm run docs:preview. Once verified, submit a PR against main to update the hosted documentation.

  6. Format release highlights in PRs

    main

    To ensure descriptive and colorful release notes in GitHub, all PRs included in a release must contain a Release Highlight section. This section must use a level 3 markdown header and be wrapped in specific HTML comments so the release parser can identify it.

    <!-- RELEASE_HIGHLIGHT_START -->
    
    ### Enhanced compatibility with CoffeeScript
    
    The MongoDB driver can now generate a cup of joe.
    
    <!-- RELEASE_HIGHLIGHT_END-->
  7. Migrate from callbacks to Promises in v5

    main

    In MongoDB Node.js Driver v5, support for callbacks has been removed from the main mongodb package in favor of a Promise-only API.

    To migrate, you should transition your code to use .then()/.catch() or async/await. The Promise-based API is identical to the callback API, except it no longer accepts a callback as the last argument and always returns a Promise.

    Recommended Migration Path:

    1. Migrate to Promise-based API: Use async/await or .then() for all database operations.
    2. Use util.callbackify: If you cannot refactor all code immediately, use Node.js's util.callbackify to wrap Promise-based methods into callback-compatible functions.
    3. Use mongodb-legacy: If you must keep callback support, install the mongodb-legacy package, which preserves v4 behavior.
    // callback-based API (v4 and earlier)
    collection.findOne({ name: 'john snow' }, (error, result) => {
      if (error) {
        /* do something with error */
        return;
      }
      /* do something with result */
    });
    
    // Promise-based API (v5+ recommended)
    collection
      .findOne({ name: 'john snow' })
      .then(result => {
        /* do something with result */
      })
      .catch(error => {
        /* do something with error */
      });
    
    // Promise-based API with async/await (v5+ recommended)
    try {
      const result = await collection.findOne({ name: 'john snow' });
      /* do something with result */
    } catch (error) {
      /* do something with error */
    }
  8. Configure alpha/prerelease publishing

    main

    To configure the repository for alpha releases, you must update both the GitHub Action and the release-please configuration.

    1. Update the release GitHub action to dispatch npm-publish.yml with the --tag alpha flag:

          - name: Dispatch npm-publish workflow
            env:
              GH_TOKEN: ${{ github.token }}
            run: |
              node ./.github/scripts/dispatch-and-wait.mjs npm-publish.yml \
                tag=alpha \
                version="${{ inputs.alphaVersion }}" \
                ref="${{ github.sha }}"

    2. Update the release-please configuration with the following parameters:

    {
      "pull-request-header": "Please run the release_notes action before releasing to generate release highlights",
      "packages": {
        ".": {
          "include-component-in-tag": false,
          "changelog-path": "HISTORY.md",
          "release-type": "node",
          "bump-minor-pre-major": false,
          "bump-patch-for-minor-pre-major": false,
          "draft": false,
          "prerelease-type": "alpha",
          "prerelease": true,
          "versioning": "prerelease"
        }
      }
    }
  9. Install the Kerberos native extension

    main

    The kerberos package is a C++ extension used for Kerberos authentication. Because it is a native extension, it requires a build environment to be installed on your system. You must be able to build Node.js itself to compile and install this module.

    Requirements:

    • UNIX: Requires the MIT Kerberos package. Consult your operating system's package manager to install the necessary libraries.
    • Windows: Uses the SSPI API, but requires a full compiler toolchain using Visual Studio C++ to install correctly.
  10. Create a backport release branch

    main

    When backporting changes to a specific minor version, follow these steps:

    1. Identify the target: Determine the target minor version and find its release tag (format v<major>.<minor>.<patch>).
    2. Create the branch: Create a new release branch from that tag using the format v<major>.<minor>.x (e.g., v6.5.x for a backport of the 6.5 release).
    3. Backport the release action:
      • Copy the current release.yml to the new branch.
      • Update all references from main to your target branch.
      • Add the new branch to the CodeQL target branches in codeql.yml.
      • Ensure any release tooling present on main is also backported.
    4. Verify: Open a PR and check CI to ensure the release action works correctly on the target branch.
  11. Perform CRUD operations with the MongoDB Driver

    main

    The following methods allow you to manage documents within a collection:

    • Insert: Use insertMany(docs) to add multiple documents.
    • Find: Use find(filter).toArray() to retrieve documents matching a query.
    • Update: Use updateOne(filter, update) to modify the first document matching the filter.
    • Delete: Use deleteMany(filter) to remove documents matching the filter.