Couchbase Node.js Client Library

repository·master·Indexed 19 days ago

https://github.com/couchbase/couchnode

The official native Node.js module for high-performance connections to Couchbase clusters using libcouchbase. It provides tools for CRUD operations via Cluster, Bucket, and Collection instances, as well as administrative management through BucketManager and AnalyticsIndexManager. The SDK supports managing analytics dataverses, datasets, and remote links (Couchbase, S3, and Azure Blob), and includes optimizations for AWS Lambda deployment.

Tokens
17K
Snippets
71
Records
87
Agent score
67%

What's inside couchbase

  1. How clusters, buckets, and collections work together

    master

    To interact with Couchbase, you follow a hierarchical connection pattern:

    1. Cluster: Create a Cluster instance using connect() with a connection string (e.g., couchbase://127.0.0.1) and authentication credentials (username, password).
    2. Bucket: Access a specific bucket via cluster.bucket('bucket_name').
    3. Collection: Access a collection within that bucket using bucket.defaultCollection() or by specifying a named collection.

    Operations (like upsert or get) are executed against the Collection instance. Most operations can be called immediately; they will be queued internally until the connection to the cluster is successfully established.

    const couchbase = require('couchbase')
    
    async function main() {
      // 1. Connect to Cluster
      const cluster = await couchbase.connect(
        'couchbase://127.0.0.1',
        {
          username: 'username',
          password: 'password',
        })
    
      // 2. Access Bucket
      const bucket = cluster.bucket('default')
      
      // 3. Access Collection
      const coll = bucket.defaultCollection()
      
      // 4. Perform Operations
      await coll.upsert('testdoc', { foo: 'bar' })
      const res = await coll.get('testdoc')
      console.log(res.content)
    }
    
    main()
  2. Implement the Logger interface for custom logging

    master

    The SDK uses a simple Logger interface. You can implement this interface to integrate the Couchbase SDK with any logging library (like Pino, Winston, or Debug). All methods are optional; the SDK safely handles loggers that only implement a subset of the methods.

    Logger Interface:

    interface Logger {
      trace?(message: string, ...args: any[]): void
      debug?(message: string, ...args: any[]): void
      info?(message: string, ...args: any[]): void
      warn?(message: string, ...args: any[]): void
      error?(message: string, ...args: any[]): void
    }
  3. Install the Couchbase Node.js Client

    master

    You can install the latest stable release of the Couchbase Node.js SDK using npm. If you need to install the development version directly from the GitHub master branch, use the git URL.

    # Install latest release
    npm install couchbase
    
    # Install development version from GitHub
    npm install "git+https://github.com/couchbase/couchnode.git#master"
  4. Enable logging via environment variables

    master

    The simplest way to enable SDK logging is by setting the CNLOGLEVEL environment variable. This will cause the SDK to create a console logger at the specified level if no other logger is provided during connection.

    Note: This is separate from the C++ core logger controlled by CBPPLOGLEVEL.

    CNLOGLEVEL=info node your-app.js
  5. Optimize SDK size for AWS Lambda

    master

    While version 4.2.5+ of the SDK is optimized for AWS Lambda size requirements, you can further reduce the deployment package size by pruning mismatched platform packages and unnecessary Couchbase dependencies (like deps and src folders) using the built-in help-prune script.

    npm explore couchbase -- npm run help-prune
  6. Configure Analytics Remote Link Encryption

    master

    When creating a CouchbaseRemoteAnalyticsLink, you can specify encryption settings using CouchbaseAnalyticsEncryptionSettings.

    • AnalyticsEncryptionLevel.None or Half: Requires username and password to be provided in the link configuration.
    • AnalyticsEncryptionLevel.Full: Requires a certificate (mandatory) and both a clientCertificate and clientKey (cannot be used with username/password authentication).
    const encryption = new CouchbaseAnalyticsEncryptionSettings({
      encryptionLevel: AnalyticsEncryptionLevel.Full,
      certificate: certBuffer,
      clientCertificate: clientCertBuffer,
      clientKey: clientKeyBuffer
    });
    
    const link = new CouchbaseRemoteAnalyticsLink({
      linkType: AnalyticsLinkType.CouchbaseRemote,
      dataverse: 'my_dataverse',
      name: 'my_link',
      hostname: 'remote-cluster-host',
      encryption: encryption
    });
  7. Handle SearchResult data and metadata

    master

    A SearchResult object contains the results of a search operation. It consists of two main parts:

    • rows: An array of SearchRow objects containing the actual data returned by the query. Note that in TypeScript, SearchRow and SearchMetaData currently require casting to any to access properties.
    • meta: A SearchMetaData object containing metadata about the query execution.
    // Example of accessing search results
    const result: SearchResult = await cluster.search(request, options);
    
    // Note: SearchRow and SearchMetaData currently require casting to any
    const rows = result.rows as any[];
    const meta = result.meta as any;
    
    rows.forEach(row => {
      console.log(row.text);
    });
  8. Manage users, groups, and roles with UserManager

    master

    The UserManager class provides an interface for managing Role-Based Access Control (RBAC) within a Couchbase cluster. You can use it to perform administrative tasks such as creating/updating users and groups, retrieving roles, and managing passwords.

    All methods in UserManager support both Promise-based usage and Node.js-style callbacks. Most methods accept an optional options object that allows you to specify a domainName, a timeout (in milliseconds), or a parentSpan for observability.

  9. Understand View query results

    master

    A view query returns a ViewResult object containing the requested data and associated metadata.

    • rows: An array of ViewRow objects. Each row contains:
      • value: The actual data returned by the view.
      • key: The key associated with the row (optional).
      • id: The document ID associated with the row (optional).
    • meta: A ViewMetaData object containing:
      • totalRows: The total number of rows matching the query in the index.
      • debug: Debug information provided by the view service.
    // Example of accessing result data
    const result: ViewResult<MyDataType, string> = await viewQuery(options);
    
    result.rows.forEach(row => {
      console.log('Key:', row.key);
      console.log('Value:', row.value);
    });
    
    console.log('Total rows found:', result.meta.totalRows);
  10. Understand PingResult and its JSON output

    master

    A PingResult object contains the results of a ping operation, organized by service type. Each service contains an array of PingEndpoint objects. You can call .toJSON() on a PingResult instance to get a JsonPingReport where latencies are converted from seconds to microseconds (latency_us).

    // Example of the structure returned by PingResult.toJSON()
    interface JsonPingReport {
      version: number;
      id: string;
      sdk: string;
      services: {
        [serviceType: string]: {
          latency_us: number;
          remote: string;
          local: string;
          id: string;
          state: string;
          namespace?: string;
          error?: string;
        }[];
      };
    }
  11. Use operation options for timeouts and tracing

    master

    Management operations in BucketManager (such as createBucket, updateBucket, dropBucket, etc.) accept an optional options object to control execution behavior.

    Common options across CreateBucketOptions, UpdateBucketOptions, DropBucketOptions, GetBucketOptions, GetAllBucketsOptions, and FlushBucketOptions include:

    • timeout: The timeout for the operation in milliseconds. If not provided, it defaults to the cluster's managementTimeout.
    • parentSpan: A RequestSpan used for distributed tracing to link this operation to a parent span.
  12. Understand Analytics query results and metadata

    master

    When executing an Analytics query, the result is returned as an AnalyticsResult<TRow> object. This object contains two primary components:

    1. rows: An array of the actual data returned by the query (of type TRow).
    2. meta: An AnalyticsMetaData object containing execution details, status, and performance metrics.

    Use the meta property to inspect the status of the query, retrieve the requestId, or access metrics and warnings generated during execution.

    // Example of accessing result data and metadata
    const result: AnalyticsResult<MyRowType> = await cluster.analytics.query('SELECT * FROM `bucket`');
    
    console.log(result.rows); // The actual data
    console.log(result.meta.status); // e.g., AnalyticsStatus.Success
    console.log(result.meta.metrics.elapsedTime); // Execution time in ms