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

The Couchbase Node.js SDK enables you to interact with a Couchbase Server cluster from the Node.js language.

The Couchbase Node.js SDK 3.0 is a complete rewrite of the API, reducing the number of overloads to present a simplified surface area, and adding support for future Couchbase Server features like Collections and Scopes (available in Couchbase Server 6.5 as a developer preview).

The 3.0 SDK also brings in promises, to reduce the complexity of asynchronous javascript in client applications, as well as extending the management APIs and bringing better debugging and logging options

Creating a New Node.js Project

Creating a Node.js project is as easy as making a directory and initializing it with npm. The next two commands will do that for us. Open up a terminal and run the following command:

mkdir node-couchbase-project && cd $_

The command above will make our directory and change our current working directory.

npm init -y

If a directory does not already have a package.json at its root, this means it is not initialized. The command above will accomplish this.

Note: We have used the -y flag to take the initialization defaults. To change any of these defaults, just open the package.json and manually make any changes.

{
  "name": "node-couchbase-project",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Installing the SDK

npm install couchbase --save

Note: 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.

Hello Couchbase

At this point we want to transition from the terminal to your code editor of choice and point to the directory we have just created named node-couchbase-project.

Let’s now create an empty file named index.js and walk through step by step adding code to enable us to connect to a bucket, add a document and retrieve it using a key-value get operation:

const couchbase = require('couchbase')
const cluster = new couchbase.Cluster(
  'couchbase://localhost',
  { username: 'Administrator', password: 'password' }
)

Couchbase uses Role Based Access Control (RBAC) to control access to resources. For the sake 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.

// get a reference to our bucket
const bucket = cluster.bucket('travel-sample')

If you are not working with the travel-sample data bucket, substitute travel-sample with your bucket-name.

// get a reference to the default collection
const collection = bucket.defaultCollection()

The latest Couchbase Server release (6.5), brings a limited Developer Preview of Collections, allowing Documents to be grouped by purpose or theme, according to a specified Collection. For our "Hello Couchbase" example we will simply use DefaultCollection, rather than a specific collection, but best practice would be to group your document by type into a single collection.

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 airline.

const airline = {
  type: 'airline',
  id: 8091,
  callsign: 'CBS',
  iata: null,
  icao: null,
  name: 'Couchbase Airways'
}

Now we will create a function that will take care of upserting that document. This function is of type async and simply awaits the result of the upsert and either logs out the result or error in our console:

const upsertDocument = async (doc) => {
  try {
    // key will equal: "airline_8091"
    const key = `${doc.type}_${doc.id}`
    const result = await collection.upsert(key, doc)
    console.log('Upsert Result: ')
    console.log(result)
  } catch (error) {
    console.error(error)
  }
}

Now, we can simply call the upsertDocument function passing in our airline document:

upsertDocument(airline)

We can turn around and retrieve that document using a key-value operation. Let’s create a function that takes a document key that is of type async and awaits the result of the get operation and either logs out the result or error in our console:

// get document function
const getAirlineByKey = async(key) => {
  try {
    const result = await collection.get(key)
    console.log('Get Result: ')
    console.log(result)
  } catch (error) {
    console.error(error)
  }
}

KV Operations are described in detail on the KV Operations page.

Now, we can simply call the getAirlineByKey function passing in our valid document key airline_8091:

// call get document function
getAirlineByKey("airline_8091")

Now we can run our code using the following command:

npm rebuild && node index.js

The results you should expect are as follows:

Upsert Result:
{
  cas: CbCas { '0': <Buffer 00 00 13 13 f4 32 10 16> },
  token: CbMutationToken {
    '0': <Buffer cc 6d 45 09 c2 ce 00 00 2c 00 00 00 00 00 00 00 a9 03 00 00 00 00 00 00 74 72 61 76 65 6c 2d 73 61 6d 70 6c 65 00 00 00 50 6b bf ef fe 7f 00 00 28 2e ... 230 more bytes>
  }
}
Get Result:
{
  cas: CbCas { '0': <Buffer 00 00 13 13 f4 32 10 16> },
  value: {
    type: 'airline',
    id: 8091,
    callsign: 'CBS',
    iata: null,
    icao: null,
    name: 'Couchbase Airways'
  }
}

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 SDK2 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.