January 19, 2025
+ 12
Install, connect, try. A quick start guide to get you up and running with Couchbase and the Node.js SDK.

Couchbase has a simple interface for creating and modifying records in a document, based upon the collection into which the documents are organized. You can read more about data modeling below, but first let’s look at those data operations, and installing the Node.js SDK.

Upsert with a Unique ID
javascript
const docId = crypto.randomUUID() await collection.upsert(docId, json)

upsert inserts (creates) the document if it does not exist, or replaces it if it does. We’ll explore creating and retrieving data records in more detail below, after walking through a quick installation.

Before You Start

Couchbase Capella, our Database-as-a-Service, lets you get on with what matters, while we take care of the administration for you. Alternately, if you need to control every aspect of deployment — or just want to run the Server in a VM on your laptop — there are several self-managed options available:

If you haven’t already got a cluster set up, the easiest route is to sign up to Couchbase Capella and deploy a free tier cluster, then come back to this page. Make a note of the endpoint to connect to, and remember the credentials for the user that you set up.

Prerequisites

  • The Node.js SDK is tested against LTS versions of Node.js — see the compatibility docs.

The code examples also assume:

  • You have signed up to Couchbase Capella.

  • You have created your own bucket, or loaded the Travel Sample dataset. Note, the Travel Sample dataset is installed automatically when deploying a Capella free tier cluster.

  • A user is created with permissions to access the cluster (at least Application Access permissions). See the Capella connection page for more details.

Couchbase Capella uses Roles to control user access to cluster resources. For the purposes of this guide, you can use the Organization Owner role automatically assigned to your account during installation of the Capella cluster. In production, Couchbase strongly recommends setting up users with more granular access roles as a best practice for data security.

Installation

More details of the installation process are in the full installation guide.

console
$ npm install couchbase --save

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

TypeScript Support

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

console
$ npm install -g typescript ts-node

Grab the Code

If you’re all set up and in a real hurry, just grab this code sample and add in your Capella details.

Complete Hello World code sample [Click to open or collapse the listing]
javascript
/* * Copyright (c) 2024 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import couchbase from 'couchbase' async function main() { // tag::connect[] const clusterConnStr = 'couchbases://cb.<your-endpoint>.cloud.couchbase.com' const username = 'username' const password = 'Password!123' const bucketName = 'travel-sample' const cluster = await couchbase.connect(clusterConnStr, { username: username, password: password, // Sets a pre-configured profile called "wanDevelopment" to help avoid latency issues // when accessing Capella from a different Wide Area Network // or Availability Zone (e.g. your laptop). configProfile: 'wanDevelopment', }) // end::connect[] // tag::bucket[] const bucket = cluster.bucket(bucketName) // end::bucket[] // tag::collection[] const collection = bucket.scope('inventory').collection('airport') // end::collection[] // tag::json[] const json = { "status": "awesome" } // end::json[] // tag::upsert[] const docId = crypto.randomUUID() await collection.upsert(docId, json) // end::upsert[] // tag::get[] try { let getResult = await collection.get(docId) console.log('Couchbase is ' + getResult.content.status) } catch (e) { if (e instanceof couchbase.DocumentNotFoundError) { console.log("Document does not exist") } else { console.log(`Error: ${e}`) } } // end::get[] const newJson = { "status": "fast" } // tag::replace[] const replaceOpts = { expiry: 10, durabilityLevel: DurabilityLevel.Majority } await collection.replace(docId, newJson, replaceOpts) // end::replace[] // tag::remove[] await collection.remove(docId) // end::remove[] } main() .catch((err) => { console.log('ERR:', err); process.exit(1); }) .then(() => process.exit());

Otherwise, read on as we introduce the CRUD API and connection to Capella or self-managed Couchbase Server.

There’s a View link to the complete sample code on GitHub above each of the snippets on these SDK pages, and a Copy icon to grab just the snippet shown.
The code samples on this page use ESModules, but the Node.js SDK is fully compatible with CommonJS as well. Simply adjust the import syntax as needed.

Connect to your Database

Connect to your Couchbase Capella operational cluster (or your local Couchbase Cluster, if you are trying out self-managed Couchbase).

javascript
const clusterConnStr = 'couchbases://cb.<your-endpoint>.cloud.couchbase.com' const username = 'username' const password = 'Password!123' const bucketName = 'travel-sample' const cluster = await couchbase.connect(clusterConnStr, { username: username, password: password, // Sets a pre-configured profile called "wanDevelopment" to help avoid latency issues // when accessing Capella from a different Wide Area Network // or Availability Zone (e.g. your laptop). configProfile: 'wanDevelopment', })

Note, the client certificate for connecting to a Capella cluster is included in the SDK installation.

The ClientOptions are covered more fully on the Client Settings page.

For a deeper look at connection options, read Managing Connections.

The connection code for getting started uses the Administrator password that you were given during set up. In any production app you should create a role restricted to the permissions needed for your app

Opening a Bucket

Following successful authentication, open the bucket with:

javascript
const bucket = cluster.bucket(bucketName)

Collections allow documents to be grouped by purpose or theme, according to a specified scope — see data modeling, below. Here we will use the airport collection within the inventory scope from travel-sample bucket as an example.

javascript
const collection = bucket.scope('inventory').collection('airport')

Create, Read, Update, Delete

Couchbase documents are organized into buckets, scopes, and collections. CRUD operations — Create, Read, Update, Delete — can be performed upon documents in a collection.

JSON

We’ll create a regular javascript object to start with:

javascript
const json = { "status": "awesome" }

Insert (Create) and Upsert

insert and upsert will both create a new document. The difference between the two is that if a document with that key already exists, the insert operation will fail, while the upsert operation will succeed, replacing the content.

We need to provide a unique ID as the key, and we’ll use a UUID here:

Creating a new document
javascript
const docId = crypto.randomUUID() await collection.upsert(docId, json)

Get (Read)

The get method reads a document from a collection. If the collection does not have a document with this ID, the get method also throws DocumentNotFoundError.

javascript
try { let getResult = await collection.get(docId) console.log('Couchbase is ' + getResult.content.status) } catch (e) { if (e instanceof couchbase.DocumentNotFoundError) { console.log("Document does not exist") } else { console.log(`Error: ${e}`) } }

Replace (Update)

The replace method updates the value of an existing document
javascript
const replaceOpts = { expiry: 10, durabilityLevel: DurabilityLevel.Majority } await collection.replace(docId, newJson, replaceOpts)
When you replace a document, it’s usually good practice to use optimistic locking. Otherwise, changes might get lost if two people change the same document at the same time.

Remove (Delete)

The remove method deletes a document from a collection:

javascript
await collection.remove(docId)

Data Modeling

Documents are organized into collections — collections of documents that belong together. You get to decide what it means to "belong." Developers usually put documents of the same type in the same collection.

For example, imagine you have two types of documents: customers and invoices. You could put the customer documents in a collection called customers, and the invoice documents in a collection called invoices.

Each document belongs to exactly one collection. A document’s ID is unique within the collection.

Different scopes can hold collections with different names. There is no relationship between collections in different scopes. Each collection belongs to just one scope and a collection’s name is unique within the scope.

More details can be found on the Data Model page.