If you’re a JavaScript dev who’s transitioning to use Node.js, you’ll want to take advantage of async functions.
That’s because asynchronous API calls don’t block your code and return promises. In this post, I’ll show you how to create async functions in Node.js that call the Couchbase SDK.
Quick Recap: Setting up a Node.js Project with Couchbase
This post continues my introductory series on using Node.js with Couchbase.
An existing Couchbase database (with travel-sample
Bucket enabled) and Node.js environment is assumed for this tutorial, but for more details see last week’s post on getting started with the Node.js SDK for Couchbase.
To catch you up, first install the Couchbase Node.js SDK using the npm
command, along with the save
option to store the dependency in your package.json
configuration file. Here’s what that looks like:
1 2 3 |
cd cb-node2 npm init -y npm install couchbase --save |
Now you’re ready to dive into the next step.
Connect to Couchbase with an Async Function
Connecting to Couchbase using the JavaScript async
function requires you to import the library in addition to three more components:
-
- Server name/address
- Username/password
- The Bucket to connect to
Wrap it all with a basic async
function and create the cluster
object.
1 2 3 4 5 6 7 |
const couchbase = require("couchbase") async function main(){ const cluster = new couchbase.Cluster("couchbase://localhost", { username: "Administrator", password: "Administrator" }); |
Once you provide the main connection info, then select the Bucket and any specific Scope or Collection (I used the default Collection throughout this example). The resulting Collection
object is used for subsequent database calls.
1 2 |
const bucket = cluster.bucket("travel-sample"); const collection = bucket.defaultCollection(); |
Getting a JSON Document
Now that you have an async function set up, let’s learn how you can get
a JSON document from Couchbase.
In order to complete a basic key-value operation, you need to know an existing document ID. For this example, let’s use the ID for Chalets Marmotte Mountain Adventure in France: hotel_5336
.
The basic get
syntax – shown in previous blog post too – is:
1 |
collection.get(key) |
To make it async, use the await
keyword inside an async
function. We’ll call this function afterwards with our hotel ID. It’s also a good habit to start capturing and printing any errors.
1 2 3 4 5 6 7 8 9 |
const getHotel = async (key) => { try { const result = await collection.get(key); console.log("Result:"); console.log(result); } catch (error) { console.error(error); } }; |
Call your new function at the end of the script. Remember, the entire script should be held within the main()
function that you call:
1 2 3 4 5 |
... await getHotel("hotel_5336"); } main(); |
Then test your async function by running and seeing the output for that particular document:
1 2 3 4 5 6 7 8 9 |
$ node app.js Result: GetResult { content: { title: 'Chamonix', name: 'Chalets Marmotte Mountain Adventure', address: '31 chemin des Rambles, Argentiere', directions: null, phone: '+33682891523', |
Upserting a JSON Document
Next, let’s cover how you can upsert
a JSON document using your async function.
Using your original script, you can add the ability to create a new document and then request it back – to show the full roundtrip. To save or add a document into the database, use the upsert
function and pass it a JSON object.
Remember, you can keep the connection and get
function and create a new function for the upsert
.
First, create the newHotel
function. As you can see below, we set it up to take the key/ID and a JSON object.
1 2 3 4 5 6 7 8 9 |
const newHotel = async (key,jsondoc) => { try { const upresult = await collection.upsert(key, jsondoc); console.log("\nUpsert result:"); console.log(upresult); } catch (error){ console.error(error); } }; |
Next, create the JSON document we will send to the Couchbase database.
1 2 3 4 5 6 |
jsondoc = { "type": "hotel", "id": 3, "name": "Le Grande", "city": "Paris, France" } |
We’ll call the new hotel entry hotel_3
when calling the new function:
1 |
await newHotel("hotel_3", jsondoc); |
If you put all this code before the getHotel
call, you can adjust the document ID for the get
function to check that the new hotel was saved.
Here is the output of creating the document and then getting the same one back:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
$ node app.js Upsert result: MutationResult { cas: CbCas<1629156064638664704>, token: CbMutationToken<771:243978275681931:85:travel-sample> } (node:3060577) [DEP0079] DeprecationWarning: Custom inspection function on Objects via .inspect() is deprecated Result: GetResult { content: { type: 'hotel', id: 3, name: 'Le Grande', city: 'Paris, France' }, cas: CbCas<1629156064638664704>, expiryTime: undefined } |
Full Code Sample
Here’s all of the example code put together from today’s post:
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 |
const couchbase = require("couchbase") async function main(){ const cluster = new couchbase.Cluster("couchbase://localhost", { username: "Administrator", password: "Administrator" }); const bucket = cluster.bucket("travel-sample"); const collection = bucket.defaultCollection(); const getHotel = async (key) => { try { const result = await collection.get(key); console.log("\nResult:"); console.log(result); } catch (error){ console.error(error); } }; const newHotel = async (key,jsondoc) => { try { const upresult = await collection.upsert(key, jsondoc); console.log("\nUpsert result:"); console.log(upresult); } catch (error){ console.error(error); } }; jsondoc = { "type": "hotel", "id": 3, "name": "Le Grande", "city": "Paris, France" } await newHotel("hotel_3", jsondoc); await getHotel("hotel_3"); } main(); |
Conclusion
Congratulations on doing a full upsert
and get
cycle in Node.js! Now you’re ready to build a more complicated application – which I’ll cover in future blog posts.
For a more in-depth developer guide, see the Couchbase Node.js SDK documentation here.
Catch up with the rest of the Node.js + Couchbase how-to series:
-
- How to Get Started with the Node.js SDK for Couchbase
- How to Create Async Get/Upsert Calls with Node.js and Couchbase
- Build a REST-Based Application with Node.js, Express and Couchbase
- How to Query JSON Data Using N1QL for Node.js and Couchbase
- How to Add Full-Text Search Functionality to Your JavaScript App
Try out Couchbase Cloud today