Sample Code

The Node.js SDK supports creation and handling of extended attributes.

Subdocument Operations and Extended Attributes

A high-level summary of extended attributes can be found in Extended Attributes. Extended attributes are handled by means of extensions to the Subdocument API.

Node.js Extended Attributes Example

The following code demonstrates how extended attributes can be used. It assumes that Couchbase Server is established on localhost; that the Full Administrator username and password are Administrator and password respectively; and that the travel-sample bucket is installed. For information on installing the travel-sample bucket, see Install Sample Buckets.

'use strict';

var couchbase = require('couchbase');

var cluster = new couchbase.Cluster('couchbase://localhost');
cluster.authenticate('Administrator', 'password');

var bucket = cluster.openBucket('travel-sample');

bucket.mutateIn('hotel_10138')
    .upsert('discounts.jsmith123', '20', {xattr: true, createParents: true})
    .upsert('discounts.pjones356', '30', {xattr: true, createParents: true})
    .insert('discounts.jbrown789', '25', {xattr: true, createParents: true})
    .remove('discounts.jbrown789', {xattr: true})
    .execute(function(err, res) {
      if (err) {
        console.log('hotel_10138 update failed', err, res);
        process.exit(1);
        }

        bucket.mutateIn('hotel_10142')
          .upsert('discounts.jsmith123', '15', {xattr: true, createParents: true})
          .upsert('discounts.pjones356', '10', {xattr: true, createParents: true})
          .execute(function(err, res) {
            if (err) {
              console.log('hotel_10142 update failed', err, res);
              process.exit(1);
              }


              var qs = 'SELECT id, meta().id AS docID FROM `travel-sample`';
              var q = couchbase.N1qlQuery.fromString(qs);
              bucket.query(q).on('row', function(row) {
                  var docID = row.docID;

                  bucket.lookupIn(docID)
                      .get('discounts.jsmith123', {xattr: true})
                      .execute(function(err, res) {
                        if (!err) {
                          var discount = res.contentByIndex(0);
                          console.log(discount + ' - ' + docID);
                        }
                      });
            });
        });
    });