English

  • English
  • 日本語
  • 한국어
  • 简体中文

Getting Started with the Node.js SDK

The Node.js client library provides fast and reliable access to documents stored inside your Couchbase Server cluster. It learns about your cluster topology automatically, so you never need to take your application down for configuration changes when your cluster expands.

With built in support for working with JSON in the Node.js client, using Couchbase Server 2.0 you have new ways to index and query data stored in the cluster. Just load our sample beer dataset and query them depending on your taste!

If you've already gotten started with the Couchbase SDK, see the quick links section below for downloads, API reference, and source code

Step 0: Get a Server

Get & Install Couchbase Server. Come back here when you're done.

Step 1: Get a Client Library

 

Step 1.0: Get libcouchbase

Windows users may skip this step as the C client library is bundled with the distribution.

Since the Node.js module builds on the 2.0 version of the Couchbase C SDK you will need to get it. The C SDK downloads and instructions are here.  Be sure to install the header files, which are frequently in a -dev or -devel package, depending on your Operating System.

Note if you have an earlier version of the Couchbase C SDK, remove it before you install the new C SDK.

Now we're ready to install the Node.js SDK. Before we continue, ensure you have the minimum requirements needed for installation.

Requirements

    Common Requirements
  • Node.js version 0.8.8 or greater. You can use
    node --version

    to output your Node.js version

  • Unix/Linux Requirements

    The following requirments are only needed if using on a Unix-type system where the extension will be built upon installation. Windows users should use the provided installer which contains pre-built binaries which already include the necessary dependencies.

    • libcouchbase 2.1.2 or greater together with its development files
    • A C Compiler

    Step 1.1: Installing using npm

    You can use npm to install using

    npm install couchbase


    Step 2: Try it out!

    Setup

    Once the Couchbase Node.js Client Library has been installed, it's easy to get started.  Create a new JavaScript file and add your require statements then follow along with us!

    var couchbase = require('couchbase');

    Creating a Couchbase Client Instance

    To create a Couchbase client instance, create a new instance of the Connection class with the host, port, password and bucket name.

    var db = new couchbase.Connection({host: 'localhost:8091', bucket: 'default'});

    The default Couchbase Server installation creates a bucket named "default" without a password, which in this case is blank.  If you created an authenticated bucket, you should specify those values in place of the default settings above. 

    The construction of a Connection instance does require some overhead as the cluster topology is discovered, so as a best practice you should retain the client object for multiple requests.

    CRUD Operations

    The primary CRUD API used by the Node.js Client is relatively straightforward. You create and update documents by supplying a key and value. You retrieve or remove documents by supplying a key.  For example, consider the JSON document that you'll find in the "beer-sample" bucket that's available when you install Couchbase Server and setup your cluster.  The key "new_holland_brewing_company-sundog" is associated with the beer document below.

    {
        "brewery_id": "new_holland_brewing_company", 
        "category": "North American Ale", 
        "updated": "2010-07-22 20:00:20", 
        "name": "Sundog", 
        "upc": 0, 
        "srm": 0.0, 
        "style": "American-Style Amber/Red Ale", 
        "abv": 5.25, 
        "type": "beer", 
        "ibu": 0.0, 
        "description": "Sundog is an amber ale as deep as the copper glow of a Lake Michigan sunset. Its biscuit malt give Sundog a toasty character and a subtle malty sweetness. Sundog brings out the best in grilled foods, caramelized onions, nutty cheese, barbecue, or your favorite pizza."
    }

    Note that credentials and bucket selection change to use the beer sample database.  If you do not have that sample database loaded, you may add it through Settings -> Sample Buckets. This will replace the previously created connection.

    var db = new couchbase.Connection({ host:'localhost:8091', bucket:'beer-sample'});

    To retrieve this document, you simply call the get method of the bucket.  The get method takes the key you wish to retrieve as well as a callback to invoke upon completion.

    Getting Documents

    db.get('new_holland_brewing_company-sundog', function(err, result) { });

    If you log the result, you will see the value along with some metadata:

    db.get('new_holland_brewing_company-sundog', function(err, result) {
    console.log(result);
    });

    Which outputs:

    { cas: { '0': 554041344, '1': 2493489702 },
      flags: 0,
      value:
       { name: 'Sundog',
         abv: 5.25,
         ibu: 0,
         srm: 0,
         upc: 0,
         type: 'beer',
         brewery_id: 'new_holland_brewing_company',
         updated: '2010-07-22 20:00:20',
         description: 'Sundog is an amber ale as deep as the copper glow of a Lake Michigan sunset. Its biscuit malt give Sundog a toasty character and a subtle malty sweetness. Sundog brings out the best in grilled foods, caramelized onions, nutty cheese, barbecue, or your favorite pizza.',
         style: 'American-Style Amber/Red Ale',
         category: 'North American Ale' } }
    You can access the actual value by using the result object's value property.

    Storing Documents

    Documents are typically stored in JSON format, which is the default storage format of the client. Of course, you're not forced to store items as JSON - but storing items as JSON allows them to be indexed by map-reduce queries (see below)

    To add a JSON document, first create a dictionary.

    var new_beer = {
       "name": "Old Yankee Ale",
       "abv": 5.00,
       "ibu": 0,
       "srm": 0,
       "upc": 0,
       "type": "beer",
       "brewery_id": "cottrell_brewing_co",
       "updated": "2012-08-30 20:00:20",
       "description": ".A medium-bodied Amber Ale",
       "style": "American-Style Amber",
       "category": "North American Ale"
    };

    For a key, we'll concatenate the brewery name in lower case, followed by a dash, followed by the beer name. We'll also normalize the name by replacing spaces with underscore and making it all lowercase. By doing so, we can directly retrieve documents by key (not just through views, which will be covered later) since we can directly determine the key name.

    var beer_id = new_beer.brewery_id.toLowerCase() + '-' +
                  new_beer.name.replace(' ', '-').toLowerCase();
    // beer_id is "cottrell_brewing_co-old_yankee_ale"

    With this new key, the JSON document may easily be stored.

    db.set(beer_id, new_beer, function(err, result) { });

    The set method will replace a key if it exists or add it if it does not, and will serialize its value to JSON by default. There are also individual add and replace methods.  The callback has a result object indicating status and other metadata, including its CAS -- a value indicating the Document's current version.

    db.set(key, new_beer, function(err, result) {
      console.log(result);
    });
    { cas: { '0': 694419456, '1': 1497366511 } }

     

    You may also remove the document by calling remove with the key:

    db.remove(beer_id, function(err, result) { });

     

    Storing Documents to Other Formats

    While the above example demonstrated how to store a Python dict as a document, you can use other datatypes as well. The Node.js library also offers built-in support for storing to utf-8 and byte (raw) formats. Specifying the format parameter instructs the library in what format your data will be stored. This can be handy if you need to store objects which don't need to be JSON (like byte strings) or objects which cannot be represented as JSON.

    A full discussion and listing of storage formats and acceptable input types can be found in the API reference and the manual.

    db.set("utf8_object", "test-string", {format: couchbase.format.utf8}, function(err, result) {
      console.log(result);
    });
    //{ cas: { '0': 6488264284, '1': 893548634} }
     
    cb.get("utf8_object", function(err, result) {
      console.log(result);
    });
    // utf8_object

     

    Working with Views

    Map/Reduce Views are used to create queryable, secondary indexes in Couchbase Server.  The primary index for documents is the key you use when performing the standard CRUD methods described above.  See the view documentation for more information on writing views. 

    For this example, a by_name view in a beer design document will be queried.  This view simply checks whether a document is a beer and has a name.  If it does, it emits the beer's name into the index.  This view will allow for beers to be queried for by name.  For example, it's now possible to ask the question "What beers start with A?"

    function (doc, meta) {
      if (doc.type && doc.type == "beer" && doc.name) {    
         emit(doc.name, null);
      }
    }

     

    Querying a view through the Node.js client is performed through the ViewQuery class which is returned from the view method.

    var query = db.view('beer', 'by_name');
     
    A ViewQuery allows you to query the view using its query method.
     
    query.query(function(err, results) {
      for(i in results)
        console.log(results[i]);
    });
    Finally, the view results can be modified by specifying an options object when first calling the query method.
     
    query.query({limit:5, key:'Sundog'}, function(err, results) {
      for(i in results)
        console.log(results[i]);
    });

     

    Then Learn More:

    The full getting started guide will cover additional getting started information. From there, move on to the tutorial, which will show how to build a full application on Couchbase Server with a JSON dataset, sample views, and modifying data.


    Quick Reference