Managing clusters

Managing clusters

You can manage a cluster by using the ClusterManager and BucketManager interfaces that are available through the manager() methods exposed in Bucket and Cluster instances.

Creating a design document

To create a view, you can use the manager() method of your bucket instance to retrieve a BucketManager instance. After you have a BucketManager instance, invoke the upsertDesignDocument method to store the design document for later querying.

var bucket = cluster.openBucket();
var bucketMgr = bucket.manager();

var ddocdata = {
  views: {
    by_name: {
      map: [ 'function(doc, meta) {',
             '  if (doc.type && doc.type == "beer") {',
             '    emit(doc.name, null);',
             '  }',
             '}'
           ].join('\n')
    },
  }
};
bucketMgr.upsertDesignDocument('ddocname', ddocdata, function(err) {
  console.log('Insertion of design document completed with error:', err);
});
Alternatively, you can just pass a JavaScript function into the design document manipulation methods and they will automatically be serialized to JavaScript. For instance, the following code snippets are functionally equivalent:
// Using a string
var ddocdata = {
  views: {
    by_name: {
      map: [ 'function(doc, meta) {',
             '  if (doc.type && doc.type == "beer") {',
             '    emit(doc.name, null);',
             '  }',
             '}'
           ].join('\n')
    },
  }
};

// Using a function
var ddocdata = {
  views: {
    by_name: {
      map: function(doc, meta) {
             if (doc.type && doc.type == "beer") {
               emit(doc.name, null);
             }
           }
    },
  }
};

Deleting a design document

To delete a design document, pass the name of the design document to delete to the removeDesignDocument method.
var bucket = cluster.openBucket();
var bucketMgr = bucket.manager();

bucketMgr.removeDesignDocument('ddocname', function(err) {
  console.log('Insertion of design document completed with error:', err);
});

Removing a single view

Removing a single view involves retrieving the full design document, removing the specific view and then replacing the existing design document with the version without your targeted view. Here is an example:
var bucket = cluster.openBucket();
var bucketMgr = bucket.manager();

function deleteView(ddocname, viewname, callback) {
  bucketMgr.getDesignDocument(ddocname, function(err, ddoc, meta) {
    if (err) {
      return callback(err);
    }

    delete ddoc.views[viewname];

    bucketMgr.upsertDesignDocument(ddocname, ddoc, function(err) {
      if (err) {
        return callback(err);
      }

      callback(null);
    });
  });
}

deleteView('ddoc', 'view', function(err) {
  console.log('Deletion completed with error:', err);
});