Interested in connecting to a Capella cluster using Node.js?
In this quickstart blog post (and I do mean quick!) I will walk you through the short set of steps to connect to a cluster in Capella with the Couchbase Node.js SDK.
Setup
Requirements
To complete this tutorial, you must have the following:
- A Couchbase Capella account – free trials are available with a simple sign-up
- Capella Cluster deployed and configured for access
- npm – Node.js package manager
Install latest long-term support (LTS) release of Node.
Download and install Node’s latest long-term support (LTS) release if you haven’t already.
If you’re installing Node for the first time, we recommend using the Node Version Manager (nvm) for getting started with Node.
- Follow the instructions for installing nvm
- Install the latest Node LTS release
1 |
$ nvm install --lts |
Create a 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:
1 |
$ mkdir node-couchbase-project && cd $_ |
The command above will make our directory and change our current working directory. The next command initializes the project directory:
1 |
$ 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.
1 2 3 4 5 6 7 8 9 10 11 12 |
{ "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" } |
Install the Couchbase Node.js SDK
The Couchbase Node.js SDK enables you to interact with a Couchbase Server cluster from the Node.js language. The Couchbase Node.js Client will run on any supported LTS version of Node.js.
To install the latest Couchbase Node.js SDK, run the following command:
1 |
$ npm install couchbase --save |
Use the –save option to have the Couchbase module added as a dependency to the project. This will help automate the installation of packages if you want to distribute your work in the future.
Connecting to Couchbase with built-in Node.js SDK
After installing the Couchbase SDK, the next step is to use the built-in SDK examples to connect to your cluster.
Find cluster connection settings
Go to the cluster’s Connect tab in the Couchbase Capella UI using these steps:
- Go to the Clusters tab in the main navigation
- Find and click on your cluster (docs-cluster13feb1 in the following screenshot). This opens the cluster with its Overview tab selected.
- Click the Connect tab in the left sidebar
In the Connection section, two endpoints are listed: One labeled Public and one labeled Private.
When connecting to the cluster over a wide area network—such as when you’re connecting to the cluster over the Internet from an application on your laptop—you will use the public endpoint.
When connecting to the cluster from within your cloud provider using a peering connection, you will use the private endpoint.
However, you will not need to copy the public endpoint for this post because it is automatically included in the built-in SDK examples we will use.
Open SDK examples
Click SDK Examples. This opens the SDK Examples fly-out menu, showing the options in this screenshot:
Each of the supported Couchbase SDK languages is represented by a tab. Under each tab, a snippet of the example code is provided. The example code is pre-populated with the cluster’s public endpoint and, with a few modifications, can quickly be used for connecting to the cluster.
Copy the example code.
Click on the tab for your desired SDK language, and copy the example code. If you’re following the examples in this guide, click the Node.js tab, and copy the example JavaScript code.
Paste the example code into a text editor and update your connection details.
The SDK example code automatically comes pre-populated with the cluster’s public endpoint and default bucket name.
Update the username and password connection settings to the database credentials you created when you configured database access earlier.
Changing the bucket (optional)
The bucketName is the name of a bucket on the cluster you will connect to. The example code comes pre-populated with the name of the default bucket: couchbasecloudbucket. This bucket will suffice for this tutorial, but if you choose to create a new bucket for this exercise, you’ll need to specify the new bucket’s name in the example code.
Database credentials must allow access to any new bucket that you add. If you configured the database credential to have read/write permissions on all buckets (as recommended), you can specify any bucket when testing out the connection.
The following is an example of a completed Node.js configuration:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
var couchbase = require('couchbase'); // Update this to your cluster const endpoint = '408f6eee-c52d-4d44-a155-691f9c511931.dataplane.couchbase.com' const username = 'admin' const password = 'P@ssw0rd' const bucketName = 'couchbasecloudbucket' // User Input ends here. // Initialize the Connection var cluster = new couchbase.Cluster('couchbases://' +endpoint+'?ssl=no_verify&console_log_level=5', {username: username, password: password}); var bucket = cluster.bucket(bucketName); var collection = bucket.defaultCollection(); function start(){ console.log('start'); return new Promise( (resolve, reject) => { resolve(); }); } async function run(){ // Create a N1QL Primary Index (but ignore if it exists) try { await cluster.queryIndexes().createPrimaryIndex(bucketName, {ignoreExists: true}); } catch (e) { } // Create and store a document try { await collection.upsert('user:king_arthur', { 'name': 'Arthur', 'email': 'kingarthur@couchbase.com', 'interests': ['Holy Grail', 'African Swallows'] }); } catch (e) { throw(e); } // Load the Document and print it // Prints Content and Metadata of the stored Document try { let getResult = await collection .get('user:king_arthur'); console.log('Got: '); console.log(getResult); } catch (e) { console.log(e); throw(e); } // Perform a N1QL Query const options = { parameters: ['African Swallows'] }; try { let queryResult = await cluster.query('SELECT name FROM '+bucketName +' WHERE $1 in interests LIMIT 1', options); queryResult.rows.forEach((row) => { console.log('Query row: ', row) }); } catch (e) { console.log(e); throw(e); } } start().then(run).then(() => { console.log("closing..."); cluster.close();}); |
Once you’ve finished updating the example code with your connection details, save it in your project directory. Be sure to use the appropriate file extension for the SDK language.
If you’re following the examples in this guide, save the file as connection-script.js in the node-couchbase-project directory that you created earlier when you installed the Couchbase Node.js SDK.
Connect to the cluster.
From the project directory, run the connection script using the following command:
1 |
node connection-script.js |
The results you should expect are as follows:
1 2 3 4 5 6 7 8 9 10 |
Got: { cas: CbCas { '0': <Buffer 08 00 64 71 50 c3 25 16> }, value: { name: 'Arthur', email: 'kingarthur@couchbase.com', interests: [ 'Holy Grail', 'African Swallows' ] } } Query row: { name: 'Arthur' } |
If you received the results above, the connection was successful, and a document was written to the bucket.
Congratulations on completing this quickstart guide! Be sure to try this out on Couchbase Capella to see how easy it can be.
Resources
Capella
To learn more about Couchbase Capella, our database-as-a-service offering:
- Sign up for a free 30-day trial if you haven’t already
- Connect your trial cluster to the Playground or connect a project to test it out for yourself
- Take a look at the Capella Learning Path!
Tutorials
The Couchbase Developer Portal has tons of tutorials/quickstart guides and learning paths to help you get started, including:
Training
We have several training options available depending on your need and level:
- Associate Node.js Developer course (free)
- Associate Architect course – language-agnostic
- All training options here
See the documentation to learn more about the Couchbase SDKs.
____________________________________________________________________________
Thank you for reading this post. At this point, you should be able to easily interact with a Couchbase Capella cluster from a Node.js script. If you have any questions or comments, please connect with us on the Couchbase Forums.