Install and Start Using the Node.js SDK with Couchbase Server

    +
    The Couchbase Node.js SDK enables you to interact with a Couchbase Server or Capella cluster from the Node.js runtime, using TypeScript or JavaScript.

    The Couchbase SDK API 3 (implemented by Node.js SDK 3.x and 4.x) is a complete rewrite of the API, reducing the number of overloads to present a simplified surface area, and adding support for Couchbase Server features like Collections and Scopes (available from Couchbase Server 7.0).

    Node.js SDK 4.x implements the same SDK API 3 bindings, but the internals are completely rewritten — using the Couchbase++ library rather than libcouchbase — to allow upcoming new features such as transactions, and fix some long-standing bugs. Please note any caveats in the migration guide.

    Hello Couchbase

    On this page we show you how to quickly get up and running — installing the Couchbase Node.js SDK, and trying out the Hello World code example against Couchbase Capella, or against a local Couchbase cluster.

    We will go through the code sample step by step, but for those in a hurry to see it, here it is:

    • Couchbase Capella (JavaScript)

    • Couchbase Capella (TypeScript)

    • Local Couchbase Server

    To connect to Couchbase Capella, be sure to get the correct endpoint as well as user, password and bucket name.

    var couchbase = require('couchbase')
    
    async function main() {
      const clusterConnStr = 'couchbases://cb.<your-endpoint>.cloud.couchbase.com'
      const username = 'Administrator'
      const password = 'Password123!'
      const bucketName = 'travel-sample'
    
      const cluster = await couchbase.connect(clusterConnStr, {
        username: username,
        password: password,
        timeouts: {
          kvTimeout: 10000, // milliseconds
        },
      })
    
      const bucket = cluster.bucket(bucketName)
    
      // Get a reference to the default collection, required only for older Couchbase server versions
      const defaultCollection = bucket.defaultCollection()
    
      const collection = bucket.scope('tenant_agent_00').collection('users')
    
      const user = {
        type: 'user',
        name: 'Michael',
        email: 'michael123@test.com',
        interests: ['Swimming', 'Rowing'],
      }
    
      // Create and store a document
      await collection.upsert('michael123', user)
    
      // Load the Document and print it
      // Prints Content and Metadata of the stored Document
      let getResult = await collection.get('michael123')
      console.log('Get Result: ', getResult)
    
      // Perform a N1QL Query
      const queryResult = await bucket
        .scope('inventory')
        .query('SELECT name FROM `airline` WHERE country=$1 LIMIT 10', {
          parameters: ['United States'],
        })
      console.log('Query Results:')
      queryResult.rows.forEach((row) => {
        console.log(row)
      })
    }
    
    // Run the main function
    main()
      .catch((err) => {
        console.log('ERR:', err)
        process.exit(1)
      })
      .then(process.exit)

    To connect to Couchbase Capella, be sure to get the correct endpoint as well as user, password and bucket name.

    'use strict'
    
    import {
      Bucket,
      Cluster,
      Collection,
      connect,
      GetResult,
      QueryResult,
    } from 'couchbase'
    
    async function main() {
      const clusterConnStr: string =
        'couchbases://cb.<your-endpoint>.cloud.couchbase.com'
      const username: string = 'Administrator'
      const password: string = 'Password123!'
      const bucketName: string = 'travel-sample'
    
      const cluster: Cluster = await connect(clusterConnStr, {
        username: username,
        password: password,
        timeouts: {
          kvTimeout: 10000, // milliseconds
        },
      })
    
      const bucket: Bucket = cluster.bucket(bucketName)
    
      const collection: Collection = bucket
        .scope('tenant_agent_00')
        .collection('users')
    
      // Get a reference to the default collection, required only for older Couchbase server versions
      const collection_default: Collection = bucket.defaultCollection()
    
      interface User {
        type: string
        name: string
        email: string
        interests: string[]
      }
    
      const user: User = {
        type: 'user',
        name: 'Michael',
        email: 'michael123@test.com',
        interests: ['Swimming', 'Rowing'],
      }
    
      await collection.upsert('michael123', user)
    
      // Load the Document and print it
      // Prints Content and Metadata of the stored document
      const getResult: GetResult = await collection.get('michael123')
      console.log('Get Result:', getResult)
    
      // Perform a N1QL Query
      const queryResult: QueryResult = await bucket
        .scope('inventory')
        .query('SELECT name FROM `airline` WHERE country=$1 LIMIT 10', {
          parameters: ['United States'],
        })
      console.log('Query Results:')
      queryResult.rows.forEach((row) => {
        console.log(row)
      })
    }
    
    // Run the main function
    main()
      .catch((err) => {
        console.log('ERR:', err)
        process.exit(1)
      })
      .then(() => process.exit(0))

    As well as the Node.js SDK, and a running instance of Couchbase Server, you will need to load up the Travel Sample Bucket using either the Web interface or the command line.

    const couchbase = require('couchbase')
    
    async function main() {
      // For a secure cluster connection, use `couchbases://<your-cluster-ip>` instead.
      const clusterConnStr = 'couchbase://localhost'
      const certificate = '/cert/path/cert.pem'
      const username = 'Administrator'
      const password = 'password'
      const bucketName = 'travel-sample'
    
      const cluster = await couchbase.connect(clusterConnStr, {
        username: username,
        password: password,
        // Uncomment if you require a secure cluster connection (TSL/SSL).
        // This is strongly recommended for production use.
        // security: {
        //   trustStorePath: certificate,
        // },
      })
    
      const bucket = cluster.bucket(bucketName)
    
      // Get a reference to the default collection, required only for older Couchbase server versions
      const collection_default = bucket.defaultCollection()
    
      const collection = bucket.scope('tenant_agent_00').collection('users')
    
      // Create and store a document
      await collection.upsert('michael123', {
        type: 'user',
        name: 'Michael',
        email: 'michael123@test.com',
        interests: ['Swimming', 'Rowing'],
      })
    
      // Load the Document and print it
      // Prints Content and Metadata of the stored Document
      const getResult = await collection.get('michael123')
      console.log('Get Result: ', getResult)
    
      // Perform a N1QL Query
      const queryResult = await bucket
        .scope('inventory')
        .query('SELECT name FROM `airline` WHERE country=$1 LIMIT 10', {
          parameters: ['United States'],
        })
      console.log('Query Results:')
      queryResult.rows.forEach((row) => {
        console.log(row)
      })
    }
    
    main()
      .catch((err) => {
        console.log('ERR:', err)
        process.exit(1)
      })
      .then(process.exit)

    The Couchbase Capella free trial version comes with the Travel Sample Bucket, and its Query indexes, loaded and ready.

    Quick Installation

    $ npm install couchbase --save

    This will download the latest Couchbase Node.js SDK, and add a dependency to your package.json.

    Information on new features, fixes, known issues, as well as information on how to install older release versions is in the release notes, and a fuller installation guide can be found here.

    TypeScript Support

    If you intend to use TypeScript instead of JavaScript, then also do the following:

    $ npm install -g typescript ts-node

    Step by Step

    Create an empty file named index.js, or alternatively index.ts for TypeScript, and walk through step by step:

    • Connect to a single node cluster, bucket, and collection

    • Add and retrieve a new document

    • Look up (SQL-type query) the new document by attribute value

    Prerequisites

    Here are all of the imports that you will need to run the sample code.

    • JavaScript

    • TypeScript

    var couchbase = require('couchbase')
    import {
      Bucket,
      Cluster,
      Collection,
      connect,
      GetResult,
      QueryResult,
    } from 'couchbase'

    Now, create an empty main() function.

    async function main() {
      // add code here...
    }

    We will update this function as we go along the steps in this guide.

    Connection

    • Couchbase Capella (JavaScript)

    • Couchbase Capella (TypeScript)

    • Local Couchbase Server

    Couchbase Capella requires mandatory use of TLS (Transport Layer Security). As of Node.js SDK version 4.1, the standard certificate required to connect to a Capella cluster is automatically included with no additional configuration.
    const clusterConnStr = 'couchbases://cb.<your-endpoint>.cloud.couchbase.com'
    const username = 'Administrator'
    const password = 'Password123!'
    const bucketName = 'travel-sample'
    
    const cluster = await couchbase.connect(clusterConnStr, {
      username: username,
      password: password,
      timeouts: {
        kvTimeout: 10000, // milliseconds
      },
    })

    Couchbase Capella uses Roles to control user access to database resources. For the purposes of this example, we can use the Organization Owner role automatically assigned to a user account during installation of the Capella cluster. This role grants full access to a Capella organization, including full data access to all projects and clusters. In a production scenario, we strongly recommend setting up users with more granular access roles as a best practice.

    For the SDK client to access cluster data, you will need to set up credentials for your database by following these steps.

    Couchbase Capella requires mandatory use of TLS (Transport Layer Security). As of Node.js SDK version 4.1, the standard certificate required to connect to a Capella cluster is automatically included with no additional configuration.
      const clusterConnStr: string =
        'couchbases://cb.<your-endpoint>.cloud.couchbase.com'
      const username: string = 'Administrator'
      const password: string = 'Password123!'
      const bucketName: string = 'travel-sample'
    
      const cluster: Cluster = await connect(clusterConnStr, {
        username: username,
        password: password,
        timeouts: {
          kvTimeout: 10000, // milliseconds
        },
      })

    Couchbase Capella uses Roles to control user access to database resources. For the purposes of this example, we can use the Organization Owner role automatically assigned to a user account during installation of the Capella cluster. This role grants full access to a Capella organization, including full data access to all projects and clusters. In a production scenario, we strongly recommend setting up users with more granular access roles as a best practice.

    For the SDK client to access cluster data, you will need to set up credentials for your database by following these steps.

    // For a secure cluster connection, use `couchbases://<your-cluster-ip>` instead.
    const clusterConnStr = 'couchbase://localhost'
    const certificate = '/cert/path/cert.pem'
    const username = 'Administrator'
    const password = 'password'
    const bucketName = 'travel-sample'
    
    const cluster = await couchbase.connect(clusterConnStr, {
      username: username,
      password: password,
      // Uncomment if you require a secure cluster connection (TSL/SSL).
      // This is strongly recommended for production use.
      // security: {
      //   trustStorePath: certificate,
      // },
    })

    Couchbase uses Role Based Access Control (RBAC) to control access to resources. For the purposes of this example, we are connecting to Couchbase using the Full Admin role created during the installation of our Couchbase Server.

    Since we are running this locally, we are using the Couchbase alias for localhost.

    Following successful authentication, the bucket can be opened:

    • JavaScript

    • TypeScript

    const bucket = cluster.bucket(bucketName)
    const bucket: Bucket = cluster.bucket(bucketName)
    We are working with the travel-sample data bucket. If you are not, update the bucketName variable used in the example with your own.

    The Node.js SDK supports full integration with the Collections feature introduced in Couchbase Server 7.0. Collections allow documents to be grouped by purpose or theme, according to a specified Scope. Here we will use the users collection within the tenant_agent_00 scope from travel-sample bucket as an example.

    • JavaScript

    • TypeScript

    const collection = bucket.scope('tenant_agent_00').collection('users')
    const collection: Collection = bucket
      .scope('tenant_agent_00')
      .collection('users')

    The code shows how you would use a named collection and scope. A named or default collection will provide the same functionality as bucket-level operations did in previous versions of Couchbase Server.

    The defaultCollection must be used when connecting to a 6.6 cluster or earlier.

    • JavaScript

    • TypeScript

    // Get a reference to the default collection, required only for older Couchbase server versions
    const defaultCollection = bucket.defaultCollection()
    // Get a reference to the default collection, required only for older Couchbase server versions
    const collection_default: Collection = bucket.defaultCollection()

    Document Addition and Retrieval

    Let’s create a document in our application that we can add to our travel-sample bucket that conforms to the structure of a document of type user.

    • JavaScript

    • TypeScript

    const user = {
      type: 'user',
      name: 'Michael',
      email: 'michael123@test.com',
      interests: ['Swimming', 'Rowing'],
    }
    interface User {
      type: string
      name: string
      email: string
      interests: string[]
    }
    
    const user: User = {
      type: 'user',
      name: 'Michael',
      email: 'michael123@test.com',
      interests: ['Swimming', 'Rowing'],
    }

    Document operations, such as storing and retrieving documents, can be done using Collection.Upsert() and Collection.Get(). Simply pass the key (and value, if applicable) to the relevant methods.

    The following code will upsert a document into the database:

    • JavaScript

    • TypeScript

    // Create and store a document
    await collection.upsert('michael123', user)
    await collection.upsert('michael123', user)

    Now, let’s retrieve that document using a key-value operation. The following runs a get for a document key and logs out the result in our console:

    • JavaScript

    • TypeScript

    // Load the Document and print it
    // Prints Content and Metadata of the stored Document
    let getResult = await collection.get('michael123')
    console.log('Get Result: ', getResult)
    // Load the Document and print it
    // Prints Content and Metadata of the stored document
    const getResult: GetResult = await collection.get('michael123')
    console.log('Get Result:', getResult)

    SQL++ Lookup

    Couchbase N1QL queries are performed by invoking Cluster.Query().

    In the code below we will query Couchbase to retrieve airlines by country and print the results.

    • JavaScript

    • TypeScript

    // Perform a N1QL Query
    const queryResult = await bucket
      .scope('inventory')
      .query('SELECT name FROM `airline` WHERE country=$1 LIMIT 10', {
        parameters: ['United States'],
      })
    console.log('Query Results:')
    queryResult.rows.forEach((row) => {
      console.log(row)
    })
    // Perform a N1QL Query
    const queryResult: QueryResult = await bucket
      .scope('inventory')
      .query('SELECT name FROM `airline` WHERE country=$1 LIMIT 10', {
        parameters: ['United States'],
      })
    console.log('Query Results:')
    queryResult.rows.forEach((row) => {
      console.log(row)
    })

    Execute!

    To ensure that we can run the main function, we add this last line of code:

    • JavaScript

    • TypeScript

    // Run the main function
    main()
      .catch((err) => {
        console.log('ERR:', err)
        process.exit(1)
      })
      .then(process.exit)
    // Run the main function
    main()
      .catch((err) => {
        console.log('ERR:', err)
        process.exit(1)
      })
      .then(() => process.exit(0))

    Now we can run our code:

    • JavaScript

    • TypeScript

    $ node index.js
    $ ts-node index.ts

    The results you should expect are as follows:

    got:  GetResult {
      content: {
        type: 'user',
        name: 'Michael',
        email: 'michael123@test.com',
        interests: [ 'Swimming', 'Rowing' ]
      },
      cas: Cas<1651756567733665792>,
      expiryTime: undefined
    }
    query row:  { name: 'Michael' }

    Next Steps

    Now you’re up and running, try one of the following:

    Additional Resources

    The API reference is generated for each release and the latest can be found here.

    Links to each release are to be found in the individual release notes.

    The Migrating from SDK API 2 to 3 page highlights the main differences to be aware of when migrating your code.

    Couchbase welcomes community contributions to the Node.js SDK. The Node.js SDK source code is available on GitHub.

    Troubleshooting