A newer version of this documentation is available.

View Latest

Managing Connections Using the Node.js SDK with Couchbase Server

    +
    This section describes how to connect the Node.JS SDK to a Couchbase cluster and bucket. It contains best practices as well as information on the connection string, SSL and other advanced connection options.

    You can specify additional options when connecting to the cluster by using the connection string. The connection string indicates to the client where cluster nodes may be found and how to connect to them. The connection string is common to other Couchbase SDKs as well as the command-line client. The connection string uses a URI-like format and is similar to a DSN used in other database systems.

    Creating a Cluster Object

    The Cluster object serves as an organizational unit for any Bucket objects created. As on the server each bucket is a member of a cluster, likewise in the SDK each Bucket object is a child of a Cluster. To create a cluster, construct it using a connection string, specifying the scheme and host(s) to connect to:

    var couchbase = require('couchbase');
    var cluster = new couchbase.Cluster('couchbase://10.0.0.1');

    Authenticating

    From Couchbase Server 5.0, you will need to authenticate the user, rather than against the bucket, as part of Role-Based Access Control. You will need to use cluster.authenticate:

    cluster.authenticate('USERNAME', 'PASSWORD');

    Connecting to a Bucket

    To connect to a bucket, invoke the Cluster object’s openBucket call. The openBucket method takes a bucket name as an argument. If your bucket is protected by a password, pass it as the second parameter to openBucket. openBucket also accepts a function as its final argument which reports any connection errors which may happen between the creation of the Bucket object and the actual connection.

    var bucket = cluster.openBucket('protectedBucket', function(err) {
      if (err) {
        console.error('Got error: %j', err);
      }
    });

    Disconnecting from a Bucket

    If the Bucket object is no longer needed, you should call the Bucket.disconnect() function. This will disconnect any existing TCP connections between the object and the server.

    Scalability and Concurrency

    Creating a new Bucket object is relatively expensive, and keeping many idle Bucket objects will negatively impact server performance (if done at a large scale). Typically your application will require only one Bucket instance per Couchbase bucket

    Unresolved include directive in modules/ROOT/pages/managing-connections.adoc - include::2.8@c-sdk::page$managing-connections.adoc[]